package com.ztgf.order.service.purchase;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.BrandInfoDTO;
import com.ztgf.commodity.models.service.IBrandInfoService;
import com.ztgf.commodity.models.vo.CommodityShopBrandVO;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.constant.SysConstant;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.file.models.bo.FileInfoSaveBO;
import com.ztgf.file.models.dto.FileInfoDTO;
import com.ztgf.file.models.service.IFileInfoService;
import com.ztgf.file.models.service.IFileService;
import com.ztgf.file.models.vo.FileInfoVO;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.purchase.PurchaseCommodityBargainLogMapper;
import com.ztgf.order.mapper.purchase.PurchaseCommodityBargainMapper;
import com.ztgf.order.mapper.purchase.PurchaseCommodityMapper;
import com.ztgf.order.mapper.purchase.PurchaseInfoMapper;
import com.ztgf.order.models.bo.purchase.*;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityBargainDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityBargainLogDTO;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityDTO;
import com.ztgf.order.models.dto.purchase.PurchaseInfoDTO;
import com.ztgf.order.models.service.IOrderInfoService;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityBargainService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityService;
import com.ztgf.order.models.service.purchase.IPurchaseInfoService;
import com.ztgf.order.models.vo.ShopCartDataVO;
import com.ztgf.order.models.vo.purchase.PurchaseCommodityBargainVO;
import com.ztgf.order.models.vo.purchase.PurchaseCommodityVO;
import com.ztgf.order.models.vo.purchase.PurchaseInfoExportVO;
import com.ztgf.order.models.vo.purchase.PurchaseInfoVO;
import com.ztgf.shopping.models.dto.audit.AuditDTO;
import com.ztgf.shopping.models.dto.shop.ShopBrandRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopCategoryRelationDTO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopSysInvoiceDTO;
import com.ztgf.shopping.models.service.shop.IShopBrandRelationService;
import com.ztgf.shopping.models.service.shop.IShopCategoryRelationService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sys.models.dto.SysAreaDTO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.sys.models.service.ISysAreaService;
import com.ztgf.sys.models.service.ISysConfigService;
import com.ztgf.sys.models.service.ISysUserService;
import com.ztgf.user.models.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static com.ztgf.order.models.enums.PurchaseImportUtil.*;

/**
 * 采购信息表控制器
 *
 * @author mxli
 * @Date 2021-05-17 10:15:52
 */
@DubboService
@Slf4j
@Lazy
public class PurchaseInfoServiceImpl extends ServiceImpl<PurchaseInfoMapper, PurchaseInfoDTO> implements IPurchaseInfoService{

    @Resource
    private YmlConfig ymlConfig;

    @Autowired
    private PurchaseCommodityMapper purchaseCommodityMapper;

    @Autowired
    private RedisUtil redisUtil;

    @DubboReference
    private IFileService fileService;

    @DubboReference
    private IShopInfoService shopInfoService;

    @Autowired
    private PurchaseCommodityBargainMapper purchaseCommodityBargainMapper;

    @Autowired
    private IPurchaseCommodityService purchaseCommodityService;

    @Autowired
    private PurchaseCommodityBargainLogMapper purchaseCommodityBargainLogMapper;

    @DubboReference
    private IShopBrandRelationService shopBrandRelationService;

    @DubboReference
    private ISysConfigService sysConfigService;

    @DubboReference
    private ISysUserService sysUserService;

    @DubboReference
    private ISysAreaService sysAreaService;

    @DubboReference
    private IBrandInfoService brandInfoService;

    @DubboReference
    private IShopCategoryRelationService shopCategoryRelationService;

    @Autowired
    private IPurchaseCommodityBargainService purchaseCommodityBargainService;

    @Autowired
    @Lazy
    private IAsyncOrderService asyncOrderService;

    @DubboReference
    private IFileInfoService fileInfoService;


    @Override
    @Transactional(rollbackFor= ServiceException.class)
    public void add(PurchaseInfoSaveBO saveBO) {

        Long shopId = null;
        BigDecimal purchaseFeeMoney = BigDecimal.ZERO;
        BigDecimal purchaseFeeMoneyScale = BigDecimal.ZERO;
        if(saveBO.getPublishType() != null && saveBO.getPublishType() != 1){ //平台自己不需要店铺id
            shopId = saveBO.getShopId();
            ShopInfoDTO shopInfoDTO = shopInfoService.selectById(shopId);
            if(shopInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            saveBO.setShopId(shopInfoDTO.getId());
            saveBO.setShopName(shopInfoDTO.getName());
            if (saveBO.getPublishType() == 0) { //用户发布（可能会出现子账号情况，统一为主账号公司名字）
                saveBO.setCreateUserId(shopInfoDTO.getUserId ());
                saveBO.setCreateUserName(shopInfoDTO.getName ());
            }
            saveBO.setPublishType(2);
            purchaseFeeMoney = shopInfoDTO.getPurchaseFeeMoney();
            purchaseFeeMoneyScale = shopInfoDTO.getPurchaseFeeMoneyScale();
        }

        if(saveBO.getCreateUserId() == null){
            Long userId = null;
            String userName = "";
            Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
            if(object == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } if(object instanceof SysUserDTO){
                userId = ((SysUserDTO) object).getId ();
                userName = ((SysUserDTO) object).getName ();
            }
            saveBO.setCreateUserId(userId);
            saveBO.setCreateUserName(userName);
        }

        PurchaseInfoDTO dto = new PurchaseInfoDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        dto.setLookTime(new Date());

        dto.setPurchaseFeeMoney(purchaseFeeMoney);
        if(dto.getPurchaseFeeMoney().compareTo(BigDecimal.ZERO) == 0){
            dto.setPurchaseFeeMoneyStatus(2);
        }

        Long organiserUserId = sysConfigService.getLongByCode(SysConstant.ORGANISER_USER_ID);
        SysUserDTO sysUserDTO = sysUserService.selectById(organiserUserId);
        //添加主办人
        dto.setOrganiserUserId(organiserUserId);
        dto.setOrganiserUserName(sysUserDTO.getName());

        boolean addSuccess =  this.insert(dto);
        if(!addSuccess){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }
        List<PurchaseCommoditySaveBO> commoditySaveBOList = saveBO.getCommoditySaveBOList();
        if(commoditySaveBOList == null || commoditySaveBOList.size() == 0){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }

        for(PurchaseCommoditySaveBO commoditySaveBO : commoditySaveBOList){
            PurchaseCommodityDTO commodityDTO = new PurchaseCommodityDTO();
            BeanUtils.copyProperties(commoditySaveBO,commodityDTO);
            commodityDTO.setId(ymlConfig.getPkId());
            commodityDTO.setPurchaseId(id);
            commodityDTO.setCreateUserId(dto.getCreateUserId());
            commodityDTO.setCreateUserName(dto.getCreateUserName());
            commodityDTO.setPurchaseFeeMoney(purchaseFeeMoney);
            commodityDTO.setPurchaseFeeMoneyScale(purchaseFeeMoneyScale);
            if(commoditySaveBO.getPdfUrl() != null){
                commodityDTO.setPdfUrl(JSON.toJSONString(commoditySaveBO.getPdfUrl()));
            }
            //商品图片
            String commodityImgUrl = commoditySaveBO.getCommodityLogoUrl ();
            if (CustomizeUtil.strIsNotNull (commodityImgUrl) && commodityImgUrl.contains(",")){
                String[] split = commodityImgUrl.split (",");
                String commodityImgUrlNew = "";
                if (split != null){
                    commodityDTO.setCommodityLogoUrl (split[0]);
                    for (int i = 1; i < split.length; i++){
                        commodityImgUrlNew = commodityImgUrlNew + split[i] + ",";
                    }
                }
                if (commodityImgUrlNew != null){
                    commodityImgUrlNew =  commodityImgUrlNew.substring(0,commodityImgUrlNew.length()-1);
                }
                commodityDTO.setCommodityImgUrl (commodityImgUrlNew);
            }
            Integer addCommodity = purchaseCommodityMapper.insert(commodityDTO);
            if(addCommodity == null || addCommodity != 1){
                throw new ServiceException(CodeEnum.FAIL_100007);
            }
        }
        // 发布询价单成功--------->发送站内消息
        List<Long> shopIds = new ArrayList<>();
        for(PurchaseCommoditySaveBO commoditySaveBO : commoditySaveBOList){
            if(commoditySaveBO.getBrandId () != null && commoditySaveBO.getBrandId () == 0){
                Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("frozen_status", 0);//未冻结的店铺
                wrapper.eq ("admin_frozen_status",0);//未冻结的店铺
                List<ShopInfoDTO> shopInfoDTOS = shopInfoService.selectList (wrapper);
                if (CustomizeUtil.listIsNotNull (shopInfoDTOS)){
                    for (ShopInfoDTO shopDto: shopInfoDTOS) {
                        shopIds.add(shopDto.getId ());
                    }
                }
            }
            Wrapper<ShopBrandRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("brand_id", commoditySaveBO.getBrandId ());
            List<ShopBrandRelationDTO> shopBrandRelationDTOS = shopBrandRelationService.selectList (wrapper);
            if(CustomizeUtil.listIsNotNull (shopBrandRelationDTOS)){
                for (ShopBrandRelationDTO shopBrandRelationDTO : shopBrandRelationDTOS) {
                    Long shopIdSell = shopBrandRelationDTO.getShopId ();
                    shopIds.add(shopIdSell);
                }
            }
        }
        List<Long> shopIdsNew = new ArrayList<Long>(new TreeSet<Long>(shopIds));
        List<Long> shopIdsNew1 = new ArrayList();
        if (saveBO.getPublishType () == 0 || saveBO.getPublishType () == 2){ //发布类型 0买家发布、1admin发布，2admin代客发布
            for (Long shopId1: shopIdsNew) {
                if (dto.getShopId () != null && !dto.getShopId ().toString ().equals (shopId1.toString ())){
                    shopIdsNew1.add(shopId1);
                }
            }
            asyncOrderService.sendPurchaseWebMessage (shopIdsNew1,dto.getId ());
        }
        if (saveBO.getPublishType () == 1){ //发布类型 0买家发布、1admin发布，2admin代客发布
            asyncOrderService.sendPurchaseWebMessage (shopIdsNew,dto.getId ());
        }

    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public void add(PurchaseInfoSaveBO saveBO,FileInfoSaveBO fileInfoBO) {//admin excel导入

        Long shopId = null;
        BigDecimal purchaseFeeMoney = BigDecimal.ZERO;
        BigDecimal purchaseFeeMoneyScale = BigDecimal.ZERO;
        if(saveBO.getPublishType() != null && saveBO.getPublishType() != 1){ //平台自己不需要店铺id
            shopId = saveBO.getShopId();
            ShopInfoDTO shopInfoDTO = shopInfoService.selectById(shopId);
            if(shopInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            saveBO.setShopId(shopInfoDTO.getId());
            saveBO.setShopName(shopInfoDTO.getName());
            if (saveBO.getPublishType() == 0) { //用户发布（可能会出现子账号情况，统一为主账号公司名字）
                saveBO.setCreateUserId(shopInfoDTO.getUserId ());
                saveBO.setCreateUserName(shopInfoDTO.getName ());
            }
            saveBO.setPublishType(2);
            purchaseFeeMoney = shopInfoDTO.getPurchaseFeeMoney();
            purchaseFeeMoneyScale = shopInfoDTO.getPurchaseFeeMoneyScale();
        }

        if(saveBO.getCreateUserId() == null){
            Long userId = null;
            String userName = "";
            Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
            if(object == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } if(object instanceof SysUserDTO){
                userId = ((SysUserDTO) object).getId ();
                userName = ((SysUserDTO) object).getName ();
            }
            saveBO.setCreateUserId(userId);
            saveBO.setCreateUserName(userName);
        }

        PurchaseInfoDTO dto = new PurchaseInfoDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        dto.setLookTime(new Date());

        dto.setPurchaseFeeMoney(purchaseFeeMoney);
        if(dto.getPurchaseFeeMoney().compareTo(BigDecimal.ZERO) == 0){
            dto.setPurchaseFeeMoneyStatus(2);
        }

        Long organiserUserId = sysConfigService.getLongByCode(SysConstant.ORGANISER_USER_ID);
        SysUserDTO sysUserDTO = sysUserService.selectById(organiserUserId);
        //添加主办人
        dto.setOrganiserUserId(organiserUserId);
        dto.setOrganiserUserName(sysUserDTO.getName());

        boolean addSuccess =  this.insert(dto);
        if(!addSuccess){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }
        List<PurchaseCommoditySaveBO> commoditySaveBOList = saveBO.getCommoditySaveBOList();
        if(commoditySaveBOList == null || commoditySaveBOList.size() == 0){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }

        for(PurchaseCommoditySaveBO commoditySaveBO : commoditySaveBOList){
            PurchaseCommodityDTO commodityDTO = new PurchaseCommodityDTO();
            BeanUtils.copyProperties(commoditySaveBO,commodityDTO);
            commodityDTO.setId(ymlConfig.getPkId());
            commodityDTO.setPurchaseId(id);
            commodityDTO.setCreateUserId(dto.getCreateUserId());
            commodityDTO.setCreateUserName(dto.getCreateUserName());
            commodityDTO.setPurchaseFeeMoney(purchaseFeeMoney);
            commodityDTO.setPurchaseFeeMoneyScale(purchaseFeeMoneyScale);

            if(commoditySaveBO.getPdfUrl() != null){
                commodityDTO.setPdfUrl(JSON.toJSONString(commoditySaveBO.getPdfUrl()));
            }
            //商品图片
            String commodityImgUrl = commoditySaveBO.getCommodityLogoUrl ();
            if (CustomizeUtil.strIsNotNull (commodityImgUrl) && commodityImgUrl.contains(",")){
                String[] split = commodityImgUrl.split (",");
                String commodityImgUrlNew = "";
                if (split != null){
                    commodityDTO.setCommodityLogoUrl (split[0]);
                    for (int i = 1; i < split.length; i++){
                        commodityImgUrlNew = commodityImgUrlNew + split[i] + ",";
                    }
                }
                if (commodityImgUrlNew != null){
                    commodityImgUrlNew =  commodityImgUrlNew.substring(0,commodityImgUrlNew.length()-1);
                }
                commodityDTO.setCommodityImgUrl (commodityImgUrlNew);
            }

            Integer addCommodity = purchaseCommodityMapper.insert(commodityDTO);
            if(addCommodity == null || addCommodity != 1){
                throw new ServiceException(CodeEnum.FAIL_100007);
            }
        }
        // 发布询价单成功--------->发送站内消息
        List<Long> shopIds = new ArrayList<>();
        for(PurchaseCommoditySaveBO commoditySaveBO : commoditySaveBOList){
            if(commoditySaveBO.getBrandId () != null && commoditySaveBO.getBrandId () == 0){
                Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("frozen_status", 0);//未冻结的店铺
                wrapper.eq ("admin_frozen_status",0);//未冻结的店铺
                List<ShopInfoDTO> shopInfoDTOS = shopInfoService.selectList (wrapper);
                if (CustomizeUtil.listIsNotNull (shopInfoDTOS)){
                    for (ShopInfoDTO shopDto: shopInfoDTOS) {
                        shopIds.add(shopDto.getId ());
                    }
                }
            }
            Wrapper<ShopBrandRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("brand_id", commoditySaveBO.getBrandId ());
            List<ShopBrandRelationDTO> shopBrandRelationDTOS = shopBrandRelationService.selectList (wrapper);
            if(CustomizeUtil.listIsNotNull (shopBrandRelationDTOS)){
                for (ShopBrandRelationDTO shopBrandRelationDTO : shopBrandRelationDTOS) {
                    Long shopIdSell = shopBrandRelationDTO.getShopId ();
                    shopIds.add(shopIdSell);
                }
            }
        }
        List<Long> shopIdsNew = new ArrayList<Long>(new TreeSet<Long>(shopIds));
        List<Long> shopIdsNew1 = new ArrayList();
        if (saveBO.getPublishType () == 0 || saveBO.getPublishType () == 2){ //发布类型 0买家发布、1admin发布，2admin代客发布
            for (Long shopId1: shopIdsNew) {
                if (dto.getShopId () != null && !dto.getShopId ().toString ().equals (shopId1.toString ())){
                    shopIdsNew1.add(shopId1);
                }
            }
            asyncOrderService.sendPurchaseWebMessage (shopIdsNew1,dto.getId ());
        }
        if (saveBO.getPublishType () == 1){ //发布类型 0买家发布、1admin发布，2admin代客发布
            asyncOrderService.sendPurchaseWebMessage (shopIdsNew,dto.getId ());
        }

        try {
            fileInfoBO.setShopId(id);//保存询价表id
            FileInfoVO vo = fileService.uploadFile(fileInfoBO);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public void add(PurchaseInfoSaveBO saveBO, AuditDTO auditDTO) {//pc审核 excel导入

        Long shopId = null;
        BigDecimal purchaseFeeMoney = BigDecimal.ZERO;
        BigDecimal purchaseFeeMoneyScale = BigDecimal.ZERO;
        if(saveBO.getPublishType() != null && saveBO.getPublishType() != 1){ //平台自己不需要店铺id
            shopId = saveBO.getShopId();
            ShopInfoDTO shopInfoDTO = shopInfoService.selectById(shopId);
            if(shopInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            saveBO.setShopId(shopInfoDTO.getId());
            saveBO.setShopName(shopInfoDTO.getName());
            if (saveBO.getPublishType() == 0) { //用户发布（可能会出现子账号情况，统一为主账号公司名字）
                saveBO.setCreateUserId(shopInfoDTO.getUserId ());
                saveBO.setCreateUserName(shopInfoDTO.getName ());
            }
            saveBO.setPublishType(2);
            purchaseFeeMoney = shopInfoDTO.getPurchaseFeeMoney();
            purchaseFeeMoneyScale = shopInfoDTO.getPurchaseFeeMoneyScale();
        }

        if(saveBO.getCreateUserId() == null){
            Long userId = null;
            String userName = "";
            Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
            if(object == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } if(object instanceof SysUserDTO){
                userId = ((SysUserDTO) object).getId ();
                userName = ((SysUserDTO) object).getName ();
            }
            saveBO.setCreateUserId(userId);
            saveBO.setCreateUserName(userName);
        }

        PurchaseInfoDTO dto = new PurchaseInfoDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        dto.setLookTime(new Date());

        dto.setPurchaseFeeMoney(purchaseFeeMoney);
        if(dto.getPurchaseFeeMoney().compareTo(BigDecimal.ZERO) == 0){
            dto.setPurchaseFeeMoneyStatus(2);
        }

        Long organiserUserId = sysConfigService.getLongByCode(SysConstant.ORGANISER_USER_ID);
        SysUserDTO sysUserDTO = sysUserService.selectById(organiserUserId);
        //添加主办人
        dto.setOrganiserUserId(organiserUserId);
        dto.setOrganiserUserName(sysUserDTO.getName());

        boolean addSuccess =  this.insert(dto);
        if(!addSuccess){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }
        List<PurchaseCommoditySaveBO> commoditySaveBOList = saveBO.getCommoditySaveBOList();
        if(commoditySaveBOList == null || commoditySaveBOList.size() == 0){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }

        for(PurchaseCommoditySaveBO commoditySaveBO : commoditySaveBOList){
            PurchaseCommodityDTO commodityDTO = new PurchaseCommodityDTO();
            BeanUtils.copyProperties(commoditySaveBO,commodityDTO);
            commodityDTO.setId(ymlConfig.getPkId());
            commodityDTO.setPurchaseId(id);
            commodityDTO.setCreateUserId(dto.getCreateUserId());
            commodityDTO.setCreateUserName(dto.getCreateUserName());
            commodityDTO.setPurchaseFeeMoney(purchaseFeeMoney);
            commodityDTO.setPurchaseFeeMoneyScale(purchaseFeeMoneyScale);

            if(commoditySaveBO.getPdfUrl() != null){
                commodityDTO.setPdfUrl(JSON.toJSONString(commoditySaveBO.getPdfUrl()));
            }
            //商品图片
            String commodityImgUrl = commoditySaveBO.getCommodityLogoUrl ();
            if (CustomizeUtil.strIsNotNull (commodityImgUrl) && commodityImgUrl.contains(",")){
                String[] split = commodityImgUrl.split (",");
                String commodityImgUrlNew = "";
                if (split != null){
                    commodityDTO.setCommodityLogoUrl (split[0]);
                    for (int i = 1; i < split.length; i++){
                        commodityImgUrlNew = commodityImgUrlNew + split[i] + ",";
                    }
                }
                if (commodityImgUrlNew != null){
                    commodityImgUrlNew =  commodityImgUrlNew.substring(0,commodityImgUrlNew.length()-1);
                }
                commodityDTO.setCommodityImgUrl (commodityImgUrlNew);
            }

            Integer addCommodity = purchaseCommodityMapper.insert(commodityDTO);
            if(addCommodity == null || addCommodity != 1){
                throw new ServiceException(CodeEnum.FAIL_100007);
            }
        }
        // 发布询价单成功--------->发送站内消息
        List<Long> shopIds = new ArrayList<>();
        for(PurchaseCommoditySaveBO commoditySaveBO : commoditySaveBOList){
            if(commoditySaveBO.getBrandId () != null && commoditySaveBO.getBrandId () == 0){
                Wrapper<ShopInfoDTO> wrapper = new EntityWrapper<>();
                wrapper.eq("frozen_status", 0);//未冻结的店铺
                wrapper.eq ("admin_frozen_status",0);//未冻结的店铺
                List<ShopInfoDTO> shopInfoDTOS = shopInfoService.selectList (wrapper);
                if (CustomizeUtil.listIsNotNull (shopInfoDTOS)){
                    for (ShopInfoDTO shopDto: shopInfoDTOS) {
                        shopIds.add(shopDto.getId ());
                    }
                }
            }
            Wrapper<ShopBrandRelationDTO> wrapper = new EntityWrapper<>();
            wrapper.eq("brand_id", commoditySaveBO.getBrandId ());
            List<ShopBrandRelationDTO> shopBrandRelationDTOS = shopBrandRelationService.selectList (wrapper);
            if(CustomizeUtil.listIsNotNull (shopBrandRelationDTOS)){
                for (ShopBrandRelationDTO shopBrandRelationDTO : shopBrandRelationDTOS) {
                    Long shopIdSell = shopBrandRelationDTO.getShopId ();
                    shopIds.add(shopIdSell);
                }
            }
        }
        List<Long> shopIdsNew = new ArrayList<Long>(new TreeSet<Long>(shopIds));
        List<Long> shopIdsNew1 = new ArrayList();
        if (saveBO.getPublishType () == 0 || saveBO.getPublishType () == 2){ //发布类型 0买家发布、1admin发布，2admin代客发布
            for (Long shopId1: shopIdsNew) {
                if (dto.getShopId () != null && !dto.getShopId ().toString ().equals (shopId1.toString ())){
                    shopIdsNew1.add(shopId1);
                }
            }
            asyncOrderService.sendPurchaseWebMessage (shopIdsNew1,dto.getId ());
        }
        if (saveBO.getPublishType () == 1){ //发布类型 0买家发布、1admin发布，2admin代客发布
            asyncOrderService.sendPurchaseWebMessage (shopIdsNew,dto.getId ());
        }

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("child_user_id", auditDTO.getId());
        wrapper.eq("business_type", 9);
        FileInfoDTO fileInfoDTO = fileInfoService.selectOne(wrapper);
        if(null != fileInfoDTO){
            fileInfoDTO.setCreateUserId(dto.getId());
            fileInfoService.updateById(fileInfoDTO);
        }

    }

    @Autowired
    private IOrderInfoService orderInfoService;

    @DubboReference
    private ISmsInfoService smsInfoService;

    /**
     * 报价
     * @param saveBO
     * @return
     */
    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveSellBargain(PurchaseCommodityBargainSaveBO saveBO) {
        if(saveBO.getPrice() == null || saveBO.getPrice().compareTo(BigDecimal.ZERO) <= 0
                || saveBO.getPurchaseCommodityId() == null
                || StrUtils.isEmpty(saveBO.getSendMobile()) || StrUtils.isEmpty(saveBO.getSendAddress())
                || saveBO.getSendAreaId() == null || saveBO.getSendDays() == null
                || saveBO.getWarranty() == null || saveBO.getWarranty() <= 0
                || saveBO.getCommodityType() == null
                || saveBO.getBrandId() == null || saveBO.getSpecificationModel() == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        //https://www.ztgfmall.com/home/goodspar?id=480090098294194176&type=0
//        String cIds = saveBO.getCommodityUrl().substring("id=");
//        Long commodityId = Long.parseLong();
//        String commodityUrl = saveBO.getCommodityUrl();
//        String[] cIds = commodityUrl.substring(commodityUrl.indexOf("id=") + 3).split("&");
        Long commodityId = saveBO.getCommodityId();
        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null || shopInfoDTO.getFrozenStatus () != 0){
            return new Result(CodeEnum.FAIL_100053);
        }


        PurchaseCommodityDTO commodityDTO = purchaseCommodityMapper.selectById(saveBO.getPurchaseCommodityId());
        if(commodityDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        //判断是否是允许预售商品
        if(commodityDTO.getPresaleStatus()  == 0 && saveBO.getCommodityType() == 1){
            return new Result(CodeEnum.FAIL_100002);
        }

        //查询这个店铺下是否存在该品牌 如果不存在 则不能报价
        if(commodityDTO.getBrandId() != null && commodityDTO.getBrandId() != 0){
            ShopBrandRelationDTO brandRelationDTO = shopBrandRelationService.getDTO(shopInfoDTO.getId(), commodityDTO.getBrandId());
            if(brandRelationDTO == null){
                return new Result(CodeEnum.FAIL_100056);
            }
        }

        saveBargain(saveBO, shopInfoDTO, commodityDTO, commodityId, userId, userName);

//        String key = "lock_bargain:" + commodityDTO.getId() + "-" + shopInfoDTO.getId();
//        try{
//            boolean lockFlag = redisUtil.setIfAbsent(key, commodityDTO.getId() + "-" + shopInfoDTO.getId(), 10, TimeUnit.SECONDS);
//            if(lockFlag) {//获取锁
//
//            } else {
//                return new Result(CodeEnum.FAIL_100054);
//            }
//        } catch (ServiceException e){
//            log.error("saveSellBargain失败", e);
//            return new Result(e.getCode(), e.getMessage());
//        } finally {
//            redisUtil.del(key);
//        }

        return new Result();
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveSellBargainOld(Long purchaseCommodityBargainId) {
        //第二次报价
        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null || shopInfoDTO.getFrozenStatus () != 0){
            return new Result(CodeEnum.FAIL_100053);
        }


        PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityBargainId);
        if(bargainDTO == null){ //添加
            return new Result(CodeEnum.FAIL_100002);
        } else {
            //是否可以报价
            if(!(bargainDTO.getRefuseBargainStatus() == 0 && bargainDTO.getBargainStatus() == 0)){
                return new Result(CodeEnum.FAIL_100055);
            }

            if(bargainDTO.getPlatBargainStatus() == 1 || bargainDTO.getPlatBargainStatus() == 2){
                return new Result(CodeEnum.FAIL_100064);
            }

            BigDecimal oldPrice = bargainDTO.getOnePrice();
            PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
            newBargainDTO.setId(purchaseCommodityBargainId);
            newBargainDTO.setPurchaseId(bargainDTO.getPurchaseId());
            newBargainDTO.setUpdateUserName(userName);
            newBargainDTO.setUpdateUserId(userId);
            newBargainDTO.setTwoPrice(oldPrice);
            newBargainDTO.setPrice(oldPrice);
            newBargainDTO.setOldPriceStatus(1);
            newBargainDTO.setBargainPriceTimes(2);
            newBargainDTO.setRevision(bargainDTO.getRevision());

            if(bargainDTO.getPlatBargainStatus() == 4){
                newBargainDTO.setPlatBargainStatus(5);//协调议价后报价
            }

            updateBargainAndLogByRevision(newBargainDTO, shopInfoDTO.getId(), 2, userId, userName, oldPrice, oldPrice, CodeEnum.FAIL_100061);

        }

        return new Result();
    }


    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveSellAcceptBargain(Long purchaseCommodityBargainId) {
        //第二次报价
        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null || shopInfoDTO.getFrozenStatus () != 0){
            return new Result(CodeEnum.FAIL_100053);
        }

        PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityBargainId);
        if(bargainDTO == null){ //添加
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        //是否可以报价
        if(!(bargainDTO.getRefuseBargainStatus() == 0 && bargainDTO.getBargainStatus() == 0)){
            throw new ServiceException(CodeEnum.FAIL_100055);
        }

        if(bargainDTO.getPlatBargainStatus() == 1 || bargainDTO.getPlatBargainStatus() == 2){
            throw new ServiceException(CodeEnum.FAIL_100064);
        }

        if(bargainDTO.getOneBargainPrice().compareTo(BigDecimal.ZERO) == 0){
            throw new ServiceException(CodeEnum.FAIL_100054);
        }

        BigDecimal oldPrice = bargainDTO.getOneBargainPrice();
        PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
        newBargainDTO.setId(purchaseCommodityBargainId);
        newBargainDTO.setUpdateUserName(userName);
        newBargainDTO.setUpdateUserId(userId);

        newBargainDTO.setPurchaseId(bargainDTO.getPurchaseId());
        newBargainDTO.setPrice(bargainDTO.getOnePrice());
        newBargainDTO.setTwoPrice(oldPrice);
        newBargainDTO.setPrice(oldPrice);
        newBargainDTO.setAcceptPriceStatus(1);

        newBargainDTO.setBargainPriceTimes(2);
        newBargainDTO.setRevision(bargainDTO.getRevision());

        if(bargainDTO.getPlatBargainStatus() == 4){
            newBargainDTO.setPlatBargainStatus(5);//协调议价后报价
        }

        updateBargainAndLogByRevision(newBargainDTO, shopInfoDTO.getId(), 2, userId, userName, oldPrice, oldPrice, CodeEnum.FAIL_100061);

        return new Result();
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveBuyBargain(Long purchaseCommodityId, BigDecimal price) {
        if(purchaseCommodityId == null || price == null || price.compareTo(BigDecimal.ZERO) <= 0){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else if(object instanceof SysUserDTO){
            userId = ((SysUserDTO) object).getId ();
            userName = ((SysUserDTO) object).getName ();
        }

        PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityId);
        if(bargainDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        PurchaseInfoDTO purchaseInfoDTO = this.selectById(bargainDTO.getPurchaseId());
        if(purchaseInfoDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long shopId = null;
        if(purchaseInfoDTO.getPublishType() != 1){
            ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
            if(shopInfoDTO == null){
                return new Result(CodeEnum.FAIL_100053);
            }

            if(!purchaseInfoDTO.getShopId().equals(shopInfoDTO.getId())){
                return new Result(CodeEnum.FAIL_100057);
            }

            shopId = shopInfoDTO.getId();
        }


        if(isFinishBargain(purchaseInfoDTO.getBargainStatus())){
            return new Result(CodeEnum.FAIL_100058);
        }

        if(isFinishBargain(bargainDTO.getBargainStatus())){
            return new Result(CodeEnum.FAIL_100058);
        }

        if(bargainDTO.getPlatBargainStatus() == 1 || bargainDTO.getPlatBargainStatus() == 2 || bargainDTO.getPlatBargainStatus() == 4){
            return new Result(CodeEnum.FAIL_100066);
        }

        BigDecimal oldPrice = bargainDTO.getPrice();
        PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
        newBargainDTO.setId(bargainDTO.getId());
        newBargainDTO.setUpdateUserName(userName);
        newBargainDTO.setUpdateUserId(userId);
        newBargainDTO.setWaitBargainPriceTimes(2);

        //修改报价或者第二次第三次报价
        int logType = 1;// 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价
        if(bargainDTO.getOneBargainPrice().compareTo(BigDecimal.ZERO) <= 0){
            logType = 1;
            newBargainDTO.setOneBargainPrice(price);
        } else {
            logType = 2;
            newBargainDTO.setTwoBargainPrice(price);
        }
        newBargainDTO.setRevision(bargainDTO.getRevision());
        newBargainDTO.setPurchaseId(bargainDTO.getPurchaseId());
        updateBargainAndLogByRevision(newBargainDTO, shopId, logType, userId, userName, oldPrice, price, CodeEnum.FAIL_100061);
        return new Result();
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveOwnBargain(Long purchaseCommodityId, BigDecimal price) {
        return saveBuyBargain(purchaseCommodityId, price);
    }

    /**
     * 取消或者完成报价
     * 如果有一个加入购物车或者购买 则完成 否则取消
     * @param purchaseIds
     * @param cancelType
     * @param cancelDescription
     * @return
     */
    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveCanceBargain(String purchaseIds, Integer cancelType, String cancelDescription) {

        String[] ids = purchaseIds.split(",");
        if(ids == null && ids.length == 0){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        Long shopId = null;
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
            ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
            if(shopInfoDTO == null){
                return new Result(CodeEnum.FAIL_100053);
            }
            shopId = shopInfoDTO.getId();
        } else {
            userId = ((SysUserDTO) object).getId ();
            userName = ((SysUserDTO) object).getName ();
        }

        saveCanceBargain(ids, shopId, userId, userName, cancelType, cancelDescription);

        return new Result();
    }

    @Transactional(rollbackFor=ServiceException.class)
    public void saveCanceBargain(String[] ids, Long shopId, Long userId, String userName, Integer cancelType, String cancelDescription){
        for(String id : ids){
            PurchaseInfoDTO dto = this.selectById(id);
            if(dto == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            if(dto.getPublishType() != 1){
//                System.out.println("----采购----"+ dto.getShopId() + "---登录------" + shopId);
                if(!dto.getShopId().equals(shopId)){
                    throw new ServiceException(CodeEnum.FAIL_100057);
                }
            }


            if(isFinishBargain(dto.getBargainStatus())){
                throw new ServiceException(CodeEnum.FAIL_100058);
            }

            saveFinishPurchaseInfo(dto, 0, userId, userName, cancelType, cancelDescription, shopId);

        }
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveOwnCancelBargain(String purchaseIds, Integer cancelType, String cancelDescription) {
        return saveCanceBargain(purchaseIds, cancelType, cancelDescription);
    }

    private void updatePurchaseInfoDTO(PurchaseInfoDTO dto){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", dto.getId());
        wrapper.eq("bargain_status", 0);
        Integer flag = this.baseMapper.update(dto, wrapper);
        if(flag == null || flag != 1){
            throw new ServiceException(CodeEnum.FAIL_100061);
        }
    }

    private void updatePurchaseCommodityDTO(PurchaseCommodityDTO dto){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", dto.getId());
        wrapper.eq("bargain_status", 0);
        Integer flag = this.purchaseCommodityMapper.update(dto, wrapper);
        if(flag == null || flag == 0){
            throw new ServiceException(CodeEnum.FAIL_100061);
        }

    }

    public void updatePurchaseCommodityBargainDTO(PurchaseCommodityBargainDTO dto){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", dto.getId());
        wrapper.eq("bargain_status", 0);
        Integer flag = this.purchaseCommodityBargainMapper.update(dto, wrapper);
        if(flag == null || flag == 0){
            throw new ServiceException(CodeEnum.FAIL_100061);
        }
    }


    /**
     * 买家拒绝议价
     * @param purchaseCommodityBargainIds
     * @return
     */
    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveBuyRefuseBargain(String purchaseCommodityBargainIds) {

        if(StrUtils.isEmpty(purchaseCommodityBargainIds)){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long shopId = null;
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();

            ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
            if(shopInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100053);
            }
            shopId = shopInfoDTO.getId();
        } else if(object instanceof SysUserDTO){
            userId = ((SysUserDTO) object).getId ();
            userName = ((SysUserDTO) object).getName ();
        }



        String[] ids = purchaseCommodityBargainIds.split(",");
        if(ids == null && ids.length == 0){
            return new Result(CodeEnum.FAIL_100002);
        }

        saveBatchBuyRefuseBargain(ids, userId, userName, shopId);
        return new Result();
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveOwnRefuseBargain(String purchaseCommodityBargainIds) {
        return saveBuyRefuseBargain(purchaseCommodityBargainIds);
    }

    @Transactional(rollbackFor=ServiceException.class)
    public void saveBatchBuyRefuseBargain(String[] ids, Long userId, String userName, Long shopId){

        for(String purchaseCommodityBargainId : ids){
            PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityBargainId);
            if(bargainDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            PurchaseInfoDTO purchaseInfoDTO = this.selectById(bargainDTO.getPurchaseId());
            if(purchaseInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            if(purchaseInfoDTO.getPublishType() != 1){//平台发布没有shopId

                if(!purchaseInfoDTO.getShopId().equals(shopId)){
                    throw new ServiceException(CodeEnum.FAIL_100057);
                }
            }

            if(isFinishBargain(purchaseInfoDTO.getBargainStatus())){
                throw new ServiceException(CodeEnum.FAIL_100058);
            }

            if(isFinishBargain(bargainDTO.getBargainStatus())){
                throw new ServiceException(CodeEnum.FAIL_100058);
            }

            PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
            newBargainDTO.setId(bargainDTO.getId());
            newBargainDTO.setUpdateUserName(userName);
            newBargainDTO.setUpdateUserId(userId);
            newBargainDTO.setRefuseBargainStatus(1);
            newBargainDTO.setBargainStatus(3);
            newBargainDTO.setRevision(bargainDTO.getRevision());
            newBargainDTO.setPurchaseId(bargainDTO.getPurchaseId());

            updateBargainAndLogByRevision(newBargainDTO, shopId, 5, userId, userName, bargainDTO.getPrice(), BigDecimal.ZERO, CodeEnum.FAIL_100061);
        }
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result savePlatBargain(String platBargain) {
        if(StrUtils.isEmpty(platBargain)){
            return new Result(CodeEnum.FAIL_100002);
        }

        List<PlatBargainBO> params = JSON.parseArray(platBargain, PlatBargainBO.class);
        if(params == null || params.size() == 0){
            return new Result(CodeEnum.FAIL_100002);
        }
        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null){
            return new Result(CodeEnum.FAIL_100053);
        }

        saveBatchPlatBargain(params, shopInfoDTO, userId, userName);
        return new Result();
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result savePlatBargain(Long purchaseCommodityBargainId) {
        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof SysUserDTO){
            userId = ((SysUserDTO) object).getId ();
            userName = ((SysUserDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityBargainId);
        if(bargainDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(isFinishBargain(bargainDTO.getBargainStatus())){
            return new Result(CodeEnum.FAIL_100058);
        }
        PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
        newBargainDTO.setId(bargainDTO.getId());
        newBargainDTO.setUpdateUserName(userName);
        newBargainDTO.setUpdateUserId(userId);
        newBargainDTO.setPlatBargainStatus(4);
        newBargainDTO.setRevision(bargainDTO.getRevision());
        newBargainDTO.setPurchaseId(bargainDTO.getPurchaseId());

        updateBargainAndLogByRevision(newBargainDTO, null, 10, userId, userName, bargainDTO.getPrice(), bargainDTO.getPrice(), CodeEnum.FAIL_100061);

        return new Result();
    }

    /**
     * 询价完成 触发条件 手动取消、手动完成、时间到期
     * @param purchaseInfoDTO
     * @param optType 0手动、1系统
     * @param userId
     * @param userName
     */
    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public void saveFinishPurchaseInfo(PurchaseInfoDTO purchaseInfoDTO, int optType, Long userId, String userName, Integer cancelType, String cancelDescription, Long shopId) {
        int purchaseStatus = 3;
        if(optType == 0){
            purchaseStatus = 2;
        }

        Map<Long, Long> finishCommodityMap = new HashMap<>();//完成的商品表
        Map<Long, Long> noFinishBargainMap = new HashMap<>();//未完成的商品报价

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("purchase_id", purchaseInfoDTO.getId());
        List<PurchaseCommodityBargainDTO> bargainDTOList = purchaseCommodityBargainMapper.selectList(wrapper);
        if(bargainDTOList != null && bargainDTOList.size() > 0){
            for(PurchaseCommodityBargainDTO bargainDTO : bargainDTOList){
                if(bargainDTO.getBargainStatus() == 0){
                    noFinishBargainMap.put(bargainDTO.getId(), bargainDTO.getId());
                } else if(bargainDTO.getBargainStatus() == 1){
                    purchaseStatus = 1;
                    finishCommodityMap.put(bargainDTO.getPurchaseCommodityId(), bargainDTO.getPurchaseCommodityId());
                }
            }
        }

        //修改商品信息
        List<PurchaseCommodityDTO> commodityDTOList = purchaseCommodityMapper.selectList(wrapper);
        if(commodityDTOList != null && commodityDTOList.size() > 0){
            for(PurchaseCommodityDTO commodityDTO : commodityDTOList){
                int status = 3;
                if(optType == 0){
                    status = 2;
                }

                if(finishCommodityMap.get(commodityDTO.getId()) != null){
                    status = 1;
                }

                //修改采购商品表
                PurchaseCommodityDTO newCommodityDTO = new PurchaseCommodityDTO();
                newCommodityDTO.setId(commodityDTO.getId());
                newCommodityDTO.setBargainStatus(status);
                newCommodityDTO.setUpdateUserId(userId);
                newCommodityDTO.setUpdateUserName(userName);
                updatePurchaseCommodityDTO(newCommodityDTO);
            }
        }

        //修改商品报价
        if(noFinishBargainMap.size() > 0){
            for(Long id : noFinishBargainMap.keySet()){
                int status = 3;
                if(optType == 0){
                    status = 2;
                }
                //修改报价商品表
                PurchaseCommodityBargainDTO bargainDTO = new PurchaseCommodityBargainDTO();
                bargainDTO.setId(id);
                bargainDTO.setBargainStatus(status);
                bargainDTO.setUpdateUserId(userId);
                bargainDTO.setUpdateUserName(userName);
                updatePurchaseCommodityBargainDTO(bargainDTO);
                //添加日志
                int logType = 9;
                if(status == 2){
                    logType = 7;
                }
                insertCommodityBargainLog(purchaseInfoDTO.getId(), bargainDTO.getId(), shopId, logType, userId, userName, BigDecimal.ZERO, BigDecimal.ZERO, CodeEnum.FAIL_100054);
            }
        }


        //修改采购表
        PurchaseInfoDTO newPurchaseInfoDTO = new PurchaseInfoDTO();
        newPurchaseInfoDTO.setId(purchaseInfoDTO.getId());
        newPurchaseInfoDTO.setBargainStatus(purchaseStatus);
        newPurchaseInfoDTO.setCancelType(cancelType);
        newPurchaseInfoDTO.setCancelDescription(cancelDescription);
        newPurchaseInfoDTO.setUpdateUserId(userId);
        newPurchaseInfoDTO.setUpdateUserName(userName);
        newPurchaseInfoDTO.setEndTime(new Date());
        updatePurchaseInfoDTO(newPurchaseInfoDTO);


    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveShoppingCart(String purchaseCommodityBargainIds) {

        if(StrUtils.isEmpty(purchaseCommodityBargainIds)){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null){
            return new Result(CodeEnum.FAIL_100053);
        }
        String[] ids = purchaseCommodityBargainIds.split(",");
        if(ids == null && ids.length == 0){
            return new Result(CodeEnum.FAIL_100002);
        }

        saveBatchShopCart(ids, shopInfoDTO.getId(), userId, userName);

        return new Result();
    }

    /**
     * 批量价购物车
     * @param ids
     * @param shopId
     * @param userId
     * @param userName
     */
    @Transactional(rollbackFor=ServiceException.class)
    public void saveBatchShopCart(String[] ids, Long shopId, Long userId, String userName){
        for(String purchaseCommodityBargainId : ids){
            PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityBargainId);
            if(bargainDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            PurchaseInfoDTO purchaseInfoDTO = this.selectById(bargainDTO.getPurchaseId());
            if(purchaseInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            if(!purchaseInfoDTO.getShopId().equals(shopId)){
                throw new ServiceException(CodeEnum.FAIL_100057);
            }

            if(!(purchaseInfoDTO.getBargainStatus() == 0 || purchaseInfoDTO.getBargainStatus() == 1)){
                throw new ServiceException(CodeEnum.FAIL_100062);
            }

            if(!(bargainDTO.getBargainStatus() == 0 || bargainDTO.getBargainStatus() == 1)){
                throw new ServiceException(CodeEnum.FAIL_100062);
            }

            if(bargainDTO.getBargainStatus() == 0){
                //修改报价商品表
                PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
                newBargainDTO.setId(bargainDTO.getId());
                newBargainDTO.setBargainStatus(1);
                newBargainDTO.setShoppingCartStatus(1);
                newBargainDTO.setUpdateUserId(userId);
                newBargainDTO.setUpdateUserName(userName);
                newBargainDTO.setRevision(bargainDTO.getRevision());
                //计算但商品服务费
                newBargainDTO.setPurchaseFeeMoneyScalePrice(setPurchaseFeeMoneyScalePrice(bargainDTO));
                //修改报价商品表
                updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100065);
                //添加日志 // 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价、9流标
                insertCommodityBargainLog(bargainDTO.getPurchaseId(), bargainDTO.getId(), shopId, 8, userId, userName, BigDecimal.ZERO, BigDecimal.ZERO, CodeEnum.FAIL_100065);
            } else {
                //修改报价商品表
                PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
                newBargainDTO.setId(bargainDTO.getId());
                newBargainDTO.setShoppingCartStatus(1);
                newBargainDTO.setUpdateUserId(userId);
                newBargainDTO.setUpdateUserName(userName);
                newBargainDTO.setRevision(bargainDTO.getRevision());
                //修改报价商品表
                updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100065);
            }

            PurchaseInfoDTO newPurchaseInfoDTO = new PurchaseInfoDTO();
            newPurchaseInfoDTO.setId(purchaseInfoDTO.getId());
            newPurchaseInfoDTO.setCancelButtonStatus(1);
            if(!this.updateById(newPurchaseInfoDTO)){
                throw new ServiceException(CodeEnum.FAIL_100065);
            }
            //TODO: 调用添加购物车接口
            purchaseCommodityBargainService.addToCart(bargainDTO.getId(),shopId);

        }

    }

    /**
     * 计算单商品服务费
     * @param bargainDTO
     * @return
     */
    private BigDecimal setPurchaseFeeMoneyScalePrice(PurchaseCommodityBargainDTO bargainDTO){
        BigDecimal feePrice = BigDecimal.ZERO;
        if(bargainDTO.getPlatBargainStatus() == 5){
            //差价
            BigDecimal flagMoney = BigDecimal.ZERO;
            if(bargainDTO.getThreePrice().compareTo(BigDecimal.ZERO) >0){
                flagMoney = bargainDTO.getTwoPrice().subtract(bargainDTO.getThreePrice());
            } else {
                flagMoney = bargainDTO.getOnePrice().subtract(bargainDTO.getTwoPrice());
            }

            if(flagMoney.compareTo(BigDecimal.ZERO) > 0){
                feePrice = flagMoney.multiply(bargainDTO.getPurchaseFeeMoneyScale());
            }
        }
        return feePrice.setScale(2, BigDecimal.ROUND_UP);
    }


    @Override
    public Result saveBuy(Long purchaseCommodityBargainId) {
        if(purchaseCommodityBargainId == null ){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null){
            return new Result(CodeEnum.FAIL_100053);
        }

        PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityBargainId);
        if(bargainDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        PurchaseInfoDTO purchaseInfoDTO = this.selectById(bargainDTO.getPurchaseId());
        if(purchaseInfoDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }

        if(!purchaseInfoDTO.getShopId().equals(shopInfoDTO.getId())){
            return new Result(CodeEnum.FAIL_100057);
        }

        if(!(purchaseInfoDTO.getBargainStatus() == 0 || purchaseInfoDTO.getBargainStatus() == 1)){
            return new Result(CodeEnum.FAIL_100062);
        }

        if(!(bargainDTO.getBargainStatus() == 0 || bargainDTO.getBargainStatus() == 1)){
            return new Result(CodeEnum.FAIL_100062);
        }

        saveBuy(bargainDTO, userId, userName, shopInfoDTO.getId(), purchaseInfoDTO.getId());

        //TODO: 调用下单接口
        Result<ShopCartDataVO> shopCartDataVO = orderInfoService.getShopCardDataForPurchaseInfo(purchaseCommodityBargainId,shopInfoDTO.getId());
        return shopCartDataVO;
    }

    @Transactional(rollbackFor=ServiceException.class)
    public void saveBuy(PurchaseCommodityBargainDTO bargainDTO, Long userId, String userName, Long shopId, Long purchaseId){
        if(bargainDTO.getBargainStatus() == 0){
            //修改报价商品表
            PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
            newBargainDTO.setId(bargainDTO.getId());
            newBargainDTO.setBargainStatus(1);
            newBargainDTO.setBuyStatus(1);
            newBargainDTO.setUpdateUserId(userId);
            newBargainDTO.setUpdateUserName(userName);
            newBargainDTO.setRevision(bargainDTO.getRevision());
            //计算但商品服务费
            newBargainDTO.setPurchaseFeeMoneyScalePrice(setPurchaseFeeMoneyScalePrice(bargainDTO));
            //修改报价商品表
            updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100063);
            //添加日志 // 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价、9流标
            insertCommodityBargainLog(bargainDTO.getPurchaseId(), bargainDTO.getId(), shopId, 8, userId, userName, BigDecimal.ZERO, BigDecimal.ZERO, CodeEnum.FAIL_100063);
        } else {
            //修改报价商品表
            PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
            newBargainDTO.setId(bargainDTO.getId());
            newBargainDTO.setBuyStatus(1);
            newBargainDTO.setUpdateUserId(userId);
            newBargainDTO.setUpdateUserName(userName);
            newBargainDTO.setRevision(bargainDTO.getRevision());
            //修改报价商品表
            updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100063);
        }

        PurchaseInfoDTO newPurchaseInfoDTO = new PurchaseInfoDTO();
        newPurchaseInfoDTO.setId(purchaseId);
        newPurchaseInfoDTO.setCancelButtonStatus(1);
        if(!this.updateById(newPurchaseInfoDTO)){
            throw new ServiceException(CodeEnum.FAIL_100063);
        }
    }

    /**
     * 修改主办人
     * @param id
     * @param sysUserId
     * @return
     */
    @Override
    public Result updateOrganiser(Long id, Long sysUserId) {
        PurchaseInfoDTO dto = new PurchaseInfoDTO();

        dto.setId(id);
        SysUserDTO sysUserDTO = sysUserService.selectById(sysUserId);
        //添加主办人
        dto.setOrganiserUserId(sysUserId);
        dto.setOrganiserUserName(sysUserDTO.getName());
        dto.setOrganiserUpdateStatus(1);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", id);
        wrapper.eq("organiser_update_status", 0);
        boolean flag = this.update(dto, wrapper);
        if(flag){
            return new Result();
        } else {
            return new Result(CodeEnum.FAIL_100008);
        }

    }

    @Override
    public Result<Page<PurchaseInfoVO>> queryBuyPageList(PurchaseInfoBuyBO bo) {
        Page<PurchaseInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        //获取店铺id
        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null){
            return new Result(CodeEnum.FAIL_100053);
        }
        bo.setShopId(shopInfoDTO.getId());
        List<PurchaseInfoVO> list = this.baseMapper.queryBuyPageList(page, bo);
        if(list != null && list.size() > 0){
            for(PurchaseInfoVO purchaseInfoVO : list){
                List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryBuyList(purchaseInfoVO.getId());

                if(commodityVOList != null && commodityVOList.size() > 0){
                    for (PurchaseCommodityVO commodityVO : commodityVOList) {
                        //图片拼接
                        if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                            commodityVO.setCommodityLogoUrl("");
                        }else {
                            if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                            }else {
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                            }
                        }
                    }
                }
                purchaseInfoVO.setCommodityVOList(commodityVOList);

            }
        }
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result<PurchaseInfoVO> getBuy(Long id) {
        PurchaseInfoVO purchaseInfoVO = this.baseMapper.get(id);
        if(purchaseInfoVO == null){
            return new Result<>();
        }

        List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryBuyList(id);
        if(commodityVOList != null && commodityVOList.size() > 0){
            for(PurchaseCommodityVO commodityVO : commodityVOList){
                //图片拼接
                if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                    commodityVO.setCommodityLogoUrl("");
                }else {
                    if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())) {
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl() + "," + commodityVO.getCommodityImgUrl());
                    } else {
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                    }
                }

                //处理区域名称
                StringBuffer areaName = new StringBuffer();
                areaName = sysAreaService.getParentArea(commodityVO.getReceiveAreaId(),areaName);
                commodityVO.setReceiveAreaName(areaName.toString());
                List<PurchaseCommodityBargainVO> bargainVOList =  purchaseCommodityBargainMapper.queryBuyList(commodityVO.getId());
                if(bargainVOList == null){
                    bargainVOList = new ArrayList<>();
                }
                for (PurchaseCommodityBargainVO bargainVO : bargainVOList){
                    List<CommodityShopBrandVO> CommodityShopBrandVOList =  brandInfoService.queryShopBrandListByShopIdAndBrandId(bargainVO.getShopId(),bargainVO.getBrandId());//查询对应品牌信息
                    areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(bargainVO.getSendAreaId(),areaName);
                    bargainVO.setSendAreaName(areaName.toString());
                    bargainVO.setCommodityShopBrandList(CommodityShopBrandVOList);
                }
                commodityVO.setBargainVOList(bargainVOList);
            }
        }
        purchaseInfoVO.setCommodityVOList(commodityVOList);
        //修改查看时间
        PurchaseInfoDTO infoDTO = new PurchaseInfoDTO();
        infoDTO.setId(id);
        Date date = new Date();
        infoDTO.setLookTime(date);
        this.updateById(infoDTO);
        return new Result(purchaseInfoVO);
    }

    @Override
    public Result<Page<PurchaseInfoVO>> querySellPageList(PurchaseInfoSellBO bo) {
        Page<PurchaseInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());

        //获取店铺id
        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
            userName = ((UserInfoDTO) object).getName ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null){
            return new Result(CodeEnum.FAIL_100053);
        }
        bo.setShopId(shopInfoDTO.getId());
        List<PurchaseInfoVO> list = this.baseMapper.querySellPageList(page, bo);
        for(PurchaseInfoVO vo : list){
            List<PurchaseCommodityVO> commodityVOList = this.purchaseCommodityMapper.querySellList(vo.getId(), shopInfoDTO.getId());
            if(commodityVOList != null && commodityVOList.size() > 0){
                for (PurchaseCommodityVO commodityVO : commodityVOList) {
                    //图片拼接
                    if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                        commodityVO.setCommodityLogoUrl("");
                    }else {
                        if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                            commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                        }else {
                            commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                        }
                    }
                }
            }
            vo.setCommodityVOList(commodityVOList);
        }
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result<PurchaseInfoVO> getSell(Long id) {


        PurchaseInfoVO purchaseInfoVO = new PurchaseInfoVO();
        PurchaseInfoDTO purchaseInfoDTO = this.selectById(id);
        if(purchaseInfoDTO == null){
            return new Result<>();
        }

        Long userId = null;
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null){
            return new Result(CodeEnum.FAIL_100053);
        }

        BeanUtils.copyProperties(purchaseInfoDTO, purchaseInfoVO);
        List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.querySellAllList(id, shopInfoDTO.getId());
        if(commodityVOList != null && commodityVOList.size() > 0){
            for(PurchaseCommodityVO commodityVO : commodityVOList){

                //图片拼接
                if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                    commodityVO.setCommodityLogoUrl("");
                }else {
                    if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                    }else {
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                    }
                }
                StringBuffer areaName = new StringBuffer();
                areaName = sysAreaService.getParentArea(commodityVO.getReceiveAreaId(),areaName);
                commodityVO.setReceiveAreaName(areaName.toString());

                List<PurchaseCommodityBargainVO> bargainVOList =  purchaseCommodityBargainMapper.querySellList(commodityVO.getId(), shopInfoDTO.getId());
                if(bargainVOList == null){
                    bargainVOList = new ArrayList<>();
                }

                for (PurchaseCommodityBargainVO bargainVO : bargainVOList){
                    areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(bargainVO.getSendAreaId(),areaName);
                    bargainVO.setSendAreaName(areaName.toString());

                }
                commodityVO.setBargainVOList(bargainVOList);
            }
        }
        purchaseInfoVO.setCommodityVOList(commodityVOList);
        return new Result(purchaseInfoVO);
    }

    @Override
    public Result<Page<PurchaseInfoVO>> queryHomePageList(PurchaseInfoHomeBO bo) {
        Long userId = null;
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object != null){
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();

            } else {
                return new Result(CodeEnum.FAIL_100002);
            }

            ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
//            if(shopInfoDTO == null){
//                return new Result(CodeEnum.FAIL_100053);
//            }
            if(shopInfoDTO != null){
                bo.setShopId(shopInfoDTO.getId());
            }

        }

        Page<PurchaseInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());

        List<PurchaseInfoVO> list = this.baseMapper.queryHomePageList(page, bo);
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result<Page<PurchaseInfoVO>> queryCmsHomePageList(PurchaseInfoHomeBO bo) {
        Page<PurchaseInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<PurchaseInfoVO> list = this.baseMapper.queryCmsHomePageList(page, bo);
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result<PurchaseInfoVO> getHome(Long id) {

        Long userId = null;
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            userId = ((UserInfoDTO) object).getId ();
        } else {
            return new Result(CodeEnum.FAIL_100002);
        }

        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        if(shopInfoDTO == null){
            return new Result(CodeEnum.FAIL_100053);
        }

        PurchaseInfoVO purchaseInfoVO = this.baseMapper.get(id);
        if(purchaseInfoVO == null){
            return new Result<>();
        }

        List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryHomeList(id);
        if(commodityVOList != null && commodityVOList.size() > 0){
            for (PurchaseCommodityVO commodityVO : commodityVOList) {
                //图片拼接
                if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                    commodityVO.setCommodityLogoUrl("");
                }else {
                    if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                    }else {
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                    }
                }
                //处理区域名称
                StringBuffer areaName = new StringBuffer();
                areaName = sysAreaService.getParentArea(commodityVO.getReceiveAreaId(),areaName);
                commodityVO.setReceiveAreaName(areaName.toString());
            }
        }
        purchaseInfoVO.setCommodityVOList(commodityVOList);

        purchaseInfoVO.setShopType(shopInfoDTO.getMerchantType());
        return new Result<>(purchaseInfoVO);
    }

    @Override
    public Result<Page<PurchaseInfoVO>> queryOwnPageList(PurchaseInfoOwnBO bo) {
        Page<PurchaseInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<PurchaseInfoVO> list = this.baseMapper.queryOwnPageList(page, bo);
        if(list != null && list.size() > 0){
            for(PurchaseInfoVO purchaseInfoVO : list){
                List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryOwnList(purchaseInfoVO.getId());
                if(commodityVOList != null && commodityVOList.size() > 0){
                    for (PurchaseCommodityVO commodityVO : commodityVOList) {
                        //图片拼接
                        if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                            commodityVO.setCommodityLogoUrl("");
                        }else {
                            if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                            }else {
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                            }
                        }
                    }
                }
                purchaseInfoVO.setCommodityVOList(commodityVOList);

                Wrapper<FileInfoDTO> fileWrapper = new EntityWrapper();
                fileWrapper.eq("create_user_id", purchaseInfoVO.getId());
                fileWrapper.eq("business_type", 9);
                FileInfoDTO fileInfoDTO = fileInfoService.selectOne(fileWrapper);
                if(null != fileInfoDTO){
                    purchaseInfoVO.setIsExcel(1);
                }else{
                    purchaseInfoVO.setIsExcel(0);
                }
            }
        }
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result<PurchaseInfoVO> getOwn(Long id) {
        PurchaseInfoVO purchaseInfoVO = this.baseMapper.get(id);
        if(purchaseInfoVO == null){
            return new Result<>();
        }

        List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryOwnList(id);
        if(commodityVOList != null && commodityVOList.size() > 0){
            for(PurchaseCommodityVO commodityVO : commodityVOList){
                //图片拼接
                if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                    commodityVO.setCommodityLogoUrl("");
                }else {
                    if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                    }else {
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                    }
                }

                StringBuffer areaName = new StringBuffer();
                areaName = sysAreaService.getParentArea(commodityVO.getReceiveAreaId(),areaName);
                commodityVO.setReceiveAreaName(areaName.toString());

                List<PurchaseCommodityBargainVO> bargainVOList =  purchaseCommodityBargainMapper.queryOwnList(commodityVO.getId());
                if(bargainVOList == null){
                    bargainVOList = new ArrayList<>();
                }
                for (PurchaseCommodityBargainVO bargainVO : bargainVOList){
                    List<CommodityShopBrandVO> CommodityShopBrandVOList =  brandInfoService.queryShopBrandListByShopIdAndBrandId(bargainVO.getShopId(),bargainVO.getBrandId());//查询对应品牌信息
                    areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(bargainVO.getSendAreaId(),areaName);
                    bargainVO.setSendAreaName(areaName.toString());
                    bargainVO.setCommodityShopBrandList(CommodityShopBrandVOList);
                }
                commodityVO.setBargainVOList(bargainVOList);
            }
        }
        purchaseInfoVO.setCommodityVOList(commodityVOList);
        //修改查看时间
        PurchaseInfoDTO infoDTO = new PurchaseInfoDTO();
        infoDTO.setId(id);
        Date date = new Date();
        infoDTO.setLookTime(date);
        this.updateById(infoDTO);
        return new Result(purchaseInfoVO);
    }

    @Override
    public Result<Page<PurchaseInfoVO>> queryAdminPageList(PurchaseInfoAdminBO bo) {
        Page<PurchaseInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<PurchaseInfoVO> list = this.baseMapper.queryAdminPageList(page, bo);
        if(list != null && list.size() > 0){
            for(PurchaseInfoVO purchaseInfoVO : list){
                List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryAdminList(purchaseInfoVO.getId());
                if(commodityVOList != null && commodityVOList.size() > 0){
                    for (PurchaseCommodityVO commodityVO : commodityVOList) {
                        //图片拼接
                        if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                            commodityVO.setCommodityLogoUrl("");
                        }else {
                            if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                            }else {
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                            }
                        }
                    }
                }
                purchaseInfoVO.setCommodityVOList(commodityVOList);
                Wrapper<FileInfoDTO> fileWrapper = new EntityWrapper();
                fileWrapper.eq("create_user_id", purchaseInfoVO.getId());
                fileWrapper.eq("business_type", 9);
                FileInfoDTO fileInfoDTO = fileInfoService.selectOne(fileWrapper);
                if(null != fileInfoDTO){
                    purchaseInfoVO.setIsExcel(1);
                }else{
                    purchaseInfoVO.setIsExcel(0);
                }
            }
        }
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result<PurchaseInfoVO> getAdmin(Long id) {
        PurchaseInfoVO purchaseInfoVO = this.baseMapper.get(id);
        if(purchaseInfoVO == null){
            return new Result<>();
        }

        List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryAdminList(id);
        if(commodityVOList != null && commodityVOList.size() > 0){
            for(PurchaseCommodityVO commodityVO : commodityVOList){
                //图片拼接
                if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                    commodityVO.setCommodityLogoUrl("");
                }else {
                    if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                    }else {
                        commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                    }
                }
                StringBuffer areaName = new StringBuffer();
                areaName = sysAreaService.getParentArea(commodityVO.getReceiveAreaId(),areaName);
                commodityVO.setReceiveAreaName(areaName.toString());

                List<PurchaseCommodityBargainVO> bargainVOList =  purchaseCommodityBargainMapper.queryAdminList(commodityVO.getId());
                if(bargainVOList == null){
                    bargainVOList = new ArrayList<>();
                }
                for (PurchaseCommodityBargainVO bargainVO : bargainVOList){
                    List<CommodityShopBrandVO> CommodityShopBrandVOList =  brandInfoService.queryShopBrandListByShopIdAndBrandId(bargainVO.getShopId(),bargainVO.getBrandId());//查询对应品牌信息
                    areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(bargainVO.getSendAreaId(),areaName);
                    bargainVO.setSendAreaName(areaName.toString());
                    bargainVO.setCommodityShopBrandList(CommodityShopBrandVOList);
                }
                commodityVO.setBargainVOList(bargainVOList);
            }
        }
        purchaseInfoVO.setCommodityVOList(commodityVOList);
        return new Result(purchaseInfoVO);
    }

    @Override
    public Result<Page<PurchaseInfoVO>> queryPlatBargainPageList(PurchaseInfoPlatBargainBO bo) {
        Page<PurchaseInfoVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<PurchaseInfoVO> list = this.baseMapper.queryPlatBargainPageList(page, bo);
        if(list != null && list.size() > 0){
            for(PurchaseInfoVO purchaseInfoVO : list){
                List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryPlatBargainList(purchaseInfoVO.getId(), bo.getType());
                if(commodityVOList != null && commodityVOList.size() > 0){
                    for (PurchaseCommodityVO commodityVO : commodityVOList) {
                        //图片拼接
                        if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                            commodityVO.setCommodityLogoUrl("");
                        }else {
                            if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                            }else {
                                commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                            }
                        }
                    }
                }
                purchaseInfoVO.setCommodityVOList(commodityVOList);
            }
        }
        page.setRecords(list);
        return new Result<>(page);
    }

    @Override
    public Result<PurchaseInfoVO> getPlatBargain(Long id) {
        PurchaseInfoVO vo = this.baseMapper.get(id);
        if(vo != null){
            List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryPlatBargainList(id, null);
            vo.setCommodityVOList(commodityVOList);
            if(commodityVOList != null && commodityVOList.size() > 0){
                for(PurchaseCommodityVO commodityVO : commodityVOList){
                    //图片拼接
                    if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                        commodityVO.setCommodityLogoUrl("");
                    }else {
                        if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                            commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                        }else {
                            commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                        }
                    }
                    StringBuffer areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(commodityVO.getReceiveAreaId(),areaName);
                    commodityVO.setReceiveAreaName(areaName.toString());

                    List<PurchaseCommodityBargainVO> bargainVOList = purchaseCommodityBargainMapper.queryPlatBargainList(commodityVO.getId());
                    if(bargainVOList == null){
                        bargainVOList = new ArrayList<>();
                    }
                    for (PurchaseCommodityBargainVO bargainVO : bargainVOList){
                        List<CommodityShopBrandVO> CommodityShopBrandVOList =  brandInfoService.queryShopBrandListByShopIdAndBrandId(bargainVO.getShopId(),bargainVO.getBrandId());//查询对应品牌信息
                        areaName = new StringBuffer();
                        areaName = sysAreaService.getParentArea(bargainVO.getSendAreaId(),areaName);
                        bargainVO.setSendAreaName(areaName.toString());
                        bargainVO.setCommodityShopBrandList(CommodityShopBrandVOList);
                    }
                    commodityVO.setBargainVOList(bargainVOList);
                }
            }
        }
        return new Result<>(vo);
    }

    @Override
    public Result<PurchaseCommodityBargainVO> getCommodityBargain(Long id,Long brandId,Long shopId) {
        PurchaseCommodityBargainVO bargainVO = purchaseCommodityBargainMapper.get(id);
        if(bargainVO != null){
            //PurchaseCommodityDTO purchaseCommodityDTO = purchaseCommodityService.selectById(bargainVO.getPurchaseCommodityId());
            StringBuffer areaName = new StringBuffer();
            areaName = sysAreaService.getParentArea(bargainVO.getSendAreaId(),areaName);
            bargainVO.setSendAreaName(areaName.toString());
        }else{
            bargainVO = new PurchaseCommodityBargainVO();
        }
        List<CommodityShopBrandVO> CommodityShopBrandVOList =  brandInfoService.queryShopBrandListByShopIdAndBrandId(shopId,brandId);
        bargainVO.setCommodityShopBrandList(CommodityShopBrandVOList);
        return new Result<>(bargainVO);
    }

    @Override
    @Transactional(rollbackFor=ServiceException.class)
    public Result saveAgentOrder(String purchaseCommodityBargainIds) {
        if(StrUtils.isEmpty(purchaseCommodityBargainIds)){
            return new Result(CodeEnum.FAIL_100002);
        }

        Long userId = null;
        String userName = "";
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        if(object == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(object instanceof UserInfoDTO){
            return new Result(CodeEnum.FAIL_100002);
        } else {

            userId = ((SysUserDTO) object).getId ();
            userName = ((SysUserDTO) object).getName ();
        }


        String[] ids = purchaseCommodityBargainIds.split(",");
        if(ids == null && ids.length == 0){
            return new Result(CodeEnum.FAIL_100002);
        }

        saveBatchAgentOrder(ids, userId, userName);

        return new Result();
    }

    @Override
    public Result<PurchaseInfoVO> getPurchaseInfo(Long id) {
        PurchaseInfoVO vo = this.baseMapper.get(id);
        if(vo != null){
            List<PurchaseCommodityVO> commodityVOList = purchaseCommodityMapper.queryHomeList(id);
            if(commodityVOList != null && commodityVOList.size() > 0) {
                for (PurchaseCommodityVO commodityVO : commodityVOList) {
                    //图片拼接
                    if (StrUtils.isEmpty(commodityVO.getCommodityLogoUrl())){
                        commodityVO.setCommodityLogoUrl("");
                    }else {
                        if (StrUtils.isNotEmpty(commodityVO.getCommodityImgUrl())){
                            commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl()+","+commodityVO.getCommodityImgUrl());
                        }else {
                            commodityVO.setCommodityLogoUrl(commodityVO.getCommodityLogoUrl());
                        }
                    }
                    StringBuffer areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(commodityVO.getReceiveAreaId(),areaName);
                    commodityVO.setReceiveAreaName(areaName.toString());
                }
            }

            vo.setCommodityVOList(commodityVOList);
        }
        return new Result<>(vo);
    }


    /**
     * 批量代客下单
     * @param ids
     * @param userId
     * @param userName
     */
    @Transactional(rollbackFor=ServiceException.class)
    public void saveBatchAgentOrder(String[] ids, Long userId, String userName){
        for(String purchaseCommodityBargainId : ids){
            PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(purchaseCommodityBargainId);
            if(bargainDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            PurchaseInfoDTO purchaseInfoDTO = this.selectById(bargainDTO.getPurchaseId());
            if(purchaseInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            if(!(purchaseInfoDTO.getBargainStatus() == 0 || purchaseInfoDTO.getBargainStatus() == 1)){
                throw new ServiceException(CodeEnum.FAIL_100062);
            }

            if(!(bargainDTO.getBargainStatus() == 0 || bargainDTO.getBargainStatus() == 1)){
                throw new ServiceException(CodeEnum.FAIL_100062);
            }

            if(bargainDTO.getBargainStatus() == 0){
                //修改报价商品表
                PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
                newBargainDTO.setId(bargainDTO.getId());
                newBargainDTO.setBargainStatus(1);
                newBargainDTO.setBuyStatus(1);
                newBargainDTO.setUpdateUserId(userId);
                newBargainDTO.setUpdateUserName(userName);
                newBargainDTO.setRevision(bargainDTO.getRevision());
                //计算但商品服务费
                newBargainDTO.setPurchaseFeeMoneyScalePrice(setPurchaseFeeMoneyScalePrice(bargainDTO));
                //修改报价商品表
                updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100067);
                //添加日志 // 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价、9流标
                insertCommodityBargainLog(bargainDTO.getPurchaseId(), bargainDTO.getId(), null, 8, userId, userName, BigDecimal.ZERO, BigDecimal.ZERO, CodeEnum.FAIL_100067);
            } else {
                //修改报价商品表
                PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
                newBargainDTO.setId(bargainDTO.getId());
                newBargainDTO.setBuyStatus(1);
                newBargainDTO.setUpdateUserId(userId);
                newBargainDTO.setUpdateUserName(userName);
                newBargainDTO.setRevision(bargainDTO.getRevision());
                //修改报价商品表
                updateCommodityBargainDTO(newBargainDTO, CodeEnum.FAIL_100067);
            }

            PurchaseInfoDTO newPurchaseInfoDTO = new PurchaseInfoDTO();
            newPurchaseInfoDTO.setId(purchaseInfoDTO.getId());
            newPurchaseInfoDTO.setCancelButtonStatus(1);
            if(!this.updateById(newPurchaseInfoDTO)){
                throw new ServiceException(CodeEnum.FAIL_100067);
            }
            //TODO: 调用添加购物车接口
        }

    }


    @Override
    public Result<List<PurchaseCommodityBargainVO>> queryCommodityBargainList(String purchaseCommodityBargainIds) {
        List<PurchaseCommodityBargainVO> list = purchaseCommodityBargainMapper.queryList(purchaseCommodityBargainIds);
        return new Result(list);
    }

    /**
     * 导出询价单方法
     * @param purchaseInfoExportVOS
     * @return
     */
    private List<PurchaseInfoExportVO>  exportPurchaseList(List<PurchaseInfoExportVO> purchaseInfoExportVOS) {
        if(CustomizeUtil.listIsNotNull (purchaseInfoExportVOS)){
            for (PurchaseInfoExportVO vo: purchaseInfoExportVOS) {
                //拼接询价单名称
                if(vo.getName () != null){
                    vo.setName (vo.getName () + "询价单");
                }
                //组装收货人区域
                if(vo.getReceiveAreaId () != null){
                    StringBuffer areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(vo.getReceiveAreaId (),areaName);
                    vo.setReceiveAreaName (areaName.toString());
                }
                //组装发货地址
                if(vo.getSendAreaId () != null){
                    StringBuffer areaName = new StringBuffer();
                    areaName = sysAreaService.getParentArea(vo.getSendAreaId (),areaName);
                    String sendAddress = areaName.toString () + vo.getSendAddress ();
                    vo.setSendAddress (sendAddress);
                }
                //时间格式转化
                if (vo.getCreateTime () != null) {
                    vo.setCreateTimeStr (DateUtils.dateToStr(vo.getCreateTime (), DateUtils.DATE_FORMAT_DATETIME));
                }
                if (vo.getExpiredTime () != null) {
                    vo.setExpiredTimeStr (DateUtils.dateToStr(vo.getExpiredTime (), DateUtils.DATE_FORMAT_DATETIME));
                }
                if (vo.getEndTime () != null) {
                    vo.setEndTimeStr (DateUtils.dateToStr(vo.getEndTime (), DateUtils.DATE_FORMAT_DATETIME));
                }
                if (vo.getReceiveExpectedTime () != null) {
                    vo.setReceiveExpectedTimeStr (DateUtils.dateToStr(vo.getReceiveExpectedTime (), DateUtils.DATE_FORMAT_DATETIME));
                }

            }
        }
        return purchaseInfoExportVOS;
    }

    /**
     * 导出买家报价单列表
     * @param bo
     * @return
     */
    @Override
    public List<PurchaseInfoExportVO> queryExportBuyList(PurchaseInfoBuyBO bo) {
        //获取店铺id
        Long userId = null;
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        userId = ((UserInfoDTO) object).getId ();
        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        bo.setShopId (shopInfoDTO.getId ());
        List<PurchaseInfoExportVO> purchaseInfoExportVOS = new ArrayList<>();
        purchaseInfoExportVOS = baseMapper.queryExportBuyList(bo);
        List<PurchaseInfoExportVO> vos = exportPurchaseList (purchaseInfoExportVOS);
        return vos;

    }



    /**
     * 导出卖家报价单列表
     * @param bo
     * @return
     */
    @Override
    public List<PurchaseInfoExportVO> queryExportSellList(PurchaseInfoSellBO bo) {

        log.error("---------queryExportSellList----------" + JSON.toJSONString(CommonParameter.getHeadParamsBO ()));
        //获取店铺id
        Long userId = null;
        Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
        userId = ((UserInfoDTO) object).getId ();
        ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
        bo.setShopId (shopInfoDTO.getId ());
        List<PurchaseInfoExportVO> purchaseInfoExportVOS = new ArrayList<>();
        purchaseInfoExportVOS = baseMapper.queryExportSellList(bo);
        List<PurchaseInfoExportVO> vos = exportPurchaseList (purchaseInfoExportVOS);
        return vos;

    }

    /**
     * 导出平台发布报价单列表
     * @param bo
     * @return
     */
    @Override
    public List<PurchaseInfoExportVO> queryExportOwnList(PurchaseInfoOwnBO bo) {
        List<PurchaseInfoExportVO> purchaseInfoExportVOS = new ArrayList<>();
        purchaseInfoExportVOS = baseMapper.queryExportOwnList(bo);
        List<PurchaseInfoExportVO> vos = exportPurchaseList (purchaseInfoExportVOS);
        return vos;

    }

    /**
     * 导出admin报价单列表
     * @param bo
     * @return
     */
    @Override
    public List<PurchaseInfoExportVO> queryExportAdminList(PurchaseInfoAdminBO bo) {
        List<PurchaseInfoExportVO> purchaseInfoExportVOS = new ArrayList<>();
        purchaseInfoExportVOS = baseMapper.queryExportAdminList(bo);
        List<PurchaseInfoExportVO> vos = exportPurchaseList (purchaseInfoExportVOS);
        return vos;
    }

    /**
     * admin导出平台砍价列表
     * @param bo
     * @return
     */
    @Override
    public List<PurchaseInfoExportVO> queryExportPlatBargainList(PurchaseInfoPlatBargainBO bo) {
        List<PurchaseInfoExportVO> purchaseInfoExportVOS = new ArrayList<>();
        purchaseInfoExportVOS = baseMapper.queryExportPlatBargainList(bo);
        List<PurchaseInfoExportVO> vos = exportPurchaseList (purchaseInfoExportVOS);
        return vos;
    }

    /**
     * 导入询价单
     * @param saveBO
     * @return
     */

    @Override
//    @SneakyThrows
    public Result saveImportPurchase(PurchaseInfoImportSaveBO saveBO, byte[] input, FileInfoSaveBO fileInfoBO) {
        Result result = analyzePurchaseExcel (saveBO, input);
        if (result.getCode () == 0 && result.getData () != null){
            PurchaseInfoSaveBO purchaseInfoSaveBO = (PurchaseInfoSaveBO)result.getData ();
            add (purchaseInfoSaveBO,fileInfoBO);
            return new Result ();
        }
        return result;
    }

    /**
     * 解析导入询价单的excel
     * @param saveBO
     * @param input
     * @return
     */
    @Override
//    @SneakyThrows
    public Result analyzePurchaseExcel(PurchaseInfoImportSaveBO saveBO, byte[] input) {
        log.info ("解析input---------------2" + input);
        Result result = new Result ();
        PurchaseInfoSaveBO purchaseInfoSaveBO = new PurchaseInfoSaveBO ();
        List<PurchaseCommoditySaveBO> purchaseCommoditySaveBOS = new ArrayList<>();

        // 解析excel
        // 将文件byte转成inputStream
        try {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
            Workbook workbook = null;
            workbook = WorkbookFactory.create(inputStream);
            inputStream.close();
            // 获取工作表对象
            Sheet sheet = workbook.getSheetAt(0);
            // 获取Excel表格中数据的行数
            int totalRow = sheet.getPhysicalNumberOfRows();
//            int totalRow = sheet.getLastRowNum();
//            totalRow ++;
            log.info ("总行数：+++++++++++++++++++++++++++" + totalRow);
            if(totalRow < 1){
                result.setCode (100072);
                result.setMsg ("询价单导入文件模板有误，请联系客服!");
                return result;
            }
            // 获取Excel表格中数据的列数
            int totalCell = sheet.getRow(0).getPhysicalNumberOfCells();
            if(totalCell != 15){
                result.setCode (100072);
                result.setMsg ("询价单导入文件模板有误，请联系客服!" );
                return result;
            }
            // 第一行
            Row oneRow = sheet.getRow(1);
            //Iterator<Row> rowIterator = sheet.rowIterator();
            for (int i = 2; i < totalRow; i++) {
                // 获取第i行
                Row row = sheet.getRow(i);
                //Row row = rowIterator.next();
//                if (null == row || "".equals(row)) {
//                    //totalRow--;
//                    continue;
//                }

                //判断i行是否为空行
                boolean rowEmpty = isRowEmpty (row);
                if (rowEmpty){
                    continue;
                }

                PurchaseCommoditySaveBO purchaseCommoditySaveBO = new PurchaseCommoditySaveBO ();
                Long provinceId = null; // 收货省份id
                Long cityId = null; // 收货市id
                Long countyId = null; // 收货区／县id
                for (int j = 0; j < totalCell; j++) {
                    // 获取标题
                    String title = this.getCellValue(oneRow.getCell(j)).trim();
                    if(ALL.indexOf (title) == -1){
                        result.setCode (100072);
                        result.setMsg ("询价单导入文件模板有误，请联系客服!");
                        return result;
                    }
                    // 获取单元格值并去除空格
                    String value = this.getCellValue(row.getCell(j)).trim();
                    log.info("value===================="+value);
                    switch (title) {
                            case BRAND_NAME: //品牌
                                if(CustomizeUtil.strIsNotNull (value)){
                                    Wrapper<BrandInfoDTO> wrapper = new EntityWrapper<> ();
                                    wrapper.like ("name",value); //模糊查询
                                    List<BrandInfoDTO> brandInfoDTOS = brandInfoService.selectList (wrapper);
                                    if(CustomizeUtil.listIsNull (brandInfoDTOS)){
                                        log.info ("品牌不存在或者品牌输入有误，请确认品牌是否正确！");
                                        result.setCode (100072);
                                        result.setMsg ("品牌不存在或者品牌输入有误，请确认品牌是否正确！");
                                        return result;
                                    }else if (brandInfoDTOS.size ()>1){
                                        log.info ("品牌不存在或者品牌输入有误，请确认品牌是否正确！");
                                        result.setCode (100072);
                                        result.setMsg ("品牌不存在或者品牌输入有误，请确认品牌是否正确！");
                                        return result;
                                    }
                                    purchaseCommoditySaveBO.setBrandId (brandInfoDTOS.get (0).getId ());
                                    purchaseCommoditySaveBO.setBrandName (value);
                                } else {
                                    purchaseCommoditySaveBO.setBrandId (0L);
                                    purchaseCommoditySaveBO.setBrandName ("其他");
                                }
                                break;
                            case COMMODITY_NAME: //商品名称
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("商品名称不能为空！");
                                    return result;
                                }
                                if(value.length () > 40){
                                    result.setCode (100072);
                                    result.setMsg ("商品名称最多不能超过40个字！");
                                    return result;
                                }
                                purchaseCommoditySaveBO.setCommodityName (value);
                                break;
                            case SPECIFICATION_MODEL: //规格型号
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("规格型号不能为空！");
                                    return result;
                                }
                                purchaseCommoditySaveBO.setSpecificationModel (value);
                                break;
                            case NUM: //需求数量
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("需求数量不能为空！");
                                    return result;
                                }
                                if(StrUtils.isNum (value)){
                                    int num = Integer.parseInt(value);
                                    if (num < 1){
                                        result.setCode (100072);
                                        result.setMsg ("输入的(需求数量)格式不符合要求，必须大等于1的整数！");
                                        return result;
                                    }
                                    purchaseCommoditySaveBO.setNum (num);
                                }else {
                                    result.setCode (100072);
                                    result.setMsg ("输入的(需求数量)格式不符合要求，必须大等于1的整数！");
                                    return result;
                                }
                                break;
                            case PRESALE_STATUS: //是否接受预售商品（非必填，默认接受）
                                // 是否可以接受预售商品0不接受，1接受
                                if(!CustomizeUtil.strIsNotNull (value)){
                                    purchaseCommoditySaveBO.setPresaleStatus (1);
                                }
                                else if (value.equals ("是")){
                                    purchaseCommoditySaveBO.setPresaleStatus (1);
                                }
                                else if (value.equals ("否")){
                                    purchaseCommoditySaveBO.setPresaleStatus (0);
                                }
                                else {
                                    log.info ("是否接受预售输入格式有误");
                                    result.setCode (100072);
                                    result.setMsg ("是否接受预售输入格式有误,请填写是或者否,如果不填写，默认接受预售！");
                                    return result;
                                }
                                break;
                            case FRIST_SCALE: //预售商品首付款比例（非必填）
                                if (CustomizeUtil.strIsNotNull (value) && purchaseCommoditySaveBO.getPresaleStatus () == 1 ){
                                        if (!StrUtils.isNum (value)){
                                            result.setCode (100072);
                                            result.setMsg ("预售商品首付款比例不符合要求,必须为整数！");
                                            return result;
                                        }
                                        BigDecimal min = new BigDecimal(0);
                                        BigDecimal max = new BigDecimal(100);
                                        BigDecimal fristScale = new BigDecimal(value);
                                        if (fristScale.compareTo(min) <= 0 || fristScale.compareTo(max) >= 0 ){
                                            result.setCode (100072);
                                            result.setMsg ("预售商品首付款比例不符合要求,必须大于0小于100！");
                                            return result;
                                        }
                                        purchaseCommoditySaveBO.setFristScale (fristScale);
                                    }
                                break;
                            case WARRANTY: //质保期（非必填：单位月）
                                if (CustomizeUtil.strIsNotNull (value)){
                                    if(StrUtils.isNum (value)){
                                        int warranty = Integer.parseInt(value);
                                        if (warranty < 1){
                                            result.setCode (100072);
                                            result.setMsg ("输入的(质保期)格式不符合要求，必须大于1！");
                                            return result;
                                        }
                                        purchaseCommoditySaveBO.setWarranty (warranty);
                                    }else {
                                        result.setCode (100072);
                                        result.setMsg ("输入的(质保期)格式不符合要求，必须为整数！");
                                        return result;
                                    }
                                }
                                break;
                            case RECEIVE_EXPECTED_TIME: //预计收货时间（非必填：如：（2021-05-22））
                                if(CustomizeUtil.strIsNotNull (value)){
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                                    try {
                                        Date receiveExpectedTime = simpleDateFormat.parse (value);
                                        Date receiveExpectedTimeEndOfDay = DateUtils.getEndOfDay (receiveExpectedTime); //获取当天最大时间
                                        Long now_m = System.currentTimeMillis(); //获取当前时间毫秒数
                                        Long now_s = receiveExpectedTimeEndOfDay.getTime(); //获取预计收货时间毫秒数
                                        if (now_m > now_s){
                                            result.setCode (100072);
                                            result.setMsg ("数据格式输入错误，正确格式示范：2021-05-22，且日期不能小于当前日期！");
                                            return result;
                                        }
                                        purchaseCommoditySaveBO.setReceiveExpectedTime (receiveExpectedTimeEndOfDay);
                                    }catch (ParseException e){
                                        result.setCode (100072);
                                        result.setMsg ("数据格式输入错误，正确格式示范：2021-05-22，且日期不能小于当前日期！");
                                        return result;
                                    }
                                }
                                break;
                            case RECEIVE_NAME: //收货人
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("收货人不能为空！");
                                    return result;
                                }
                                purchaseCommoditySaveBO.setReceiveName (value);
                                break;
                            case RECEIVE_MOBILE: //收货电话
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("收货电话不能为空！");
                                    return result;
                                }
//                                if (!StrUtils.isMobile (value)){
//                                    result.setCode (100072);
//                                    result.setMsg ("输入的(收货电话)格式有误！！！！");
//                                    return result;
//                                }
                                purchaseCommoditySaveBO.setReceiveMobile (value);
                                break;
                            case RECEIVE_PROVINCE: //收货省份
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("收货省份不能为空！");
                                    return result;
                                }
                                else {
                                    Wrapper<SysAreaDTO> wrapper = new EntityWrapper<> ();
                                    wrapper.eq ("name",value);
                                    wrapper.eq ("type",1);//类型：0国家，1省市、2市、3区
                                    List<SysAreaDTO> sysAreaDTOS = sysAreaService.selectList (wrapper);
                                    if (CustomizeUtil.listIsNull (sysAreaDTOS)){
                                        log.info ("输入收货省份格式错误，正确格式示范：四川省！");
                                        result.setCode (100072);
                                        result.setMsg ("输入收货省份格式错误，正确格式示范：四川省！");
                                        return result;
                                    }else if (sysAreaDTOS.size () > 1){
                                        log.info ("输入收货省份格式错误，正确格式示范：四川省！");
                                        result.setCode (100072);
                                        result.setMsg ("输入收货省份格式错误，正确格式示范：四川省！");
                                        return result;
                                    }
                                    provinceId = sysAreaDTOS.get (0).getId (); // 收货省份id
                                    purchaseCommoditySaveBO.setReceiveAreaName (value); //拼接收货人区域--省份
                                    purchaseCommoditySaveBO.setReceiveAreaId (provinceId);
                                }
                                break;
                            case RECEIVE_CITY: //收货市（直辖市填写市辖区）
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("收货市（直辖市填写市辖区）不能为空！");
                                    return result;
                                }
                                else {
                                    Wrapper<SysAreaDTO> wrapper = new EntityWrapper<> ();
                                    wrapper.eq ("name",value);
                                    wrapper.eq ("type",2);//类型：0国家，1省市、2市、3区
                                    wrapper.eq ("parent_id",provinceId); //匹配省份id
                                    List<SysAreaDTO> sysAreaDTOS = sysAreaService.selectList (wrapper);
                                    if (CustomizeUtil.listIsNull (sysAreaDTOS)){
                                        log.info ("输入收货市格式错误，正确格式示范：成都市！");
                                        result.setCode (100072);
                                        result.setMsg ("输入收货市格式错误，正确格式示范：成都市！");
                                        return result;
                                    }else if (sysAreaDTOS.size () > 1){
                                        log.info ("输入收货市格式错误，正确格式示范：成都市！");
                                        result.setCode (100072);
                                        result.setMsg ("输入收货市格式错误，正确格式示范：成都市！");
                                        return result;
                                    }
                                    cityId = sysAreaDTOS.get (0).getId (); // 收货市id
                                    purchaseCommoditySaveBO.setReceiveAreaName (purchaseCommoditySaveBO.getReceiveAreaName ()+value); //拼接收货人区域--市
                                    purchaseCommoditySaveBO.setReceiveAreaId (cityId);
                                }
                                break;
                            case RECEIVE_COUNTY: //收货区／县
                                if (CustomizeUtil.strIsNotNull (value)){
                                    Wrapper<SysAreaDTO> wrapper = new EntityWrapper<> ();
                                    wrapper.eq ("name",value);
                                    wrapper.eq ("type",3);//类型：0国家，1省市、2市、3区
                                    wrapper.eq ("parent_id",cityId); //匹配市id
                                    List<SysAreaDTO> sysAreaDTOS = sysAreaService.selectList (wrapper);
                                    if (CustomizeUtil.listIsNull (sysAreaDTOS)){
                                        log.info ("输入收货区格式错误，正确格式示范：双流区！");
                                        result.setCode (100072);
                                        result.setMsg ("输入收货区格式错误，正确格式示范：双流区！");
                                        return result;
                                    }else if (sysAreaDTOS.size () > 1){
                                        log.info ("输入收货区格式错误，正确格式示范：双流区！");
                                        result.setCode (100072);
                                        result.setMsg ("输入收货区格式错误，正确格式示范：双流区！");
                                        return result;
                                    }
                                    countyId = sysAreaDTOS.get (0).getId (); // 收货市id
                                    purchaseCommoditySaveBO.setReceiveAreaName (purchaseCommoditySaveBO.getReceiveAreaName ()+value); //拼接收货人区域--区
                                    purchaseCommoditySaveBO.setReceiveAreaId (countyId);
                                }
                                break;
                            case RECEIVE_ADDRESS: //收货详细地址
                                if (!CustomizeUtil.strIsNotNull (value)){
                                    result.setCode (100072);
                                    result.setMsg ("收货详细地址不能为空！");
                                    return result;
                                }
                                purchaseCommoditySaveBO.setReceiveAddress (value);
                                break;
                            case REMARK: //备注（非必填）
                                if (CustomizeUtil.strIsNotNull (value)){
                                    purchaseCommoditySaveBO.setRemark (value);
                                }
                                break;
                            default:
                                break;
                    }
                }
                if(purchaseCommoditySaveBO != null){
                    purchaseCommoditySaveBOS.add(purchaseCommoditySaveBO);
                }
            }
            if(CustomizeUtil.listIsNull (purchaseCommoditySaveBOS)){
                log.info ("询价单导入文件模板有误，请联系客服!");
                result.setCode (100072);
                result.setMsg ("询价单导入文件模板有误，请联系客服!");
                return result;
            }
            purchaseInfoSaveBO.setCommoditySaveBOList (purchaseCommoditySaveBOS);
            purchaseInfoSaveBO.setCreateUserId (saveBO.getCreateUserId ()); //创建用户id
            purchaseInfoSaveBO.setCreateUserName (saveBO.getCreateUserName ()); //创建用户名称
            purchaseInfoSaveBO.setShopId (saveBO.getShopId ()); //店铺ID
            purchaseInfoSaveBO.setShopName (saveBO.getShopName ()); //公司名称
            purchaseInfoSaveBO.setPublishType (saveBO.getPublishType ()); //发布类型 0买家发布、1admin发布，2admin代客发布
            purchaseInfoSaveBO.setAcceptEditStatus (saveBO.getAcceptEditStatus ()); //是否同意平台修改 0不同意、1同意 （必填）
            purchaseInfoSaveBO.setName (saveBO.getName ()); //询价单名称
            purchaseInfoSaveBO.setExpiredTime (saveBO.getExpiredTime ());  // 过期时间

            result.setData (purchaseInfoSaveBO);
        }
        catch (Exception e) {
            log.info ("询价单导入文件模板有误，请联系客服!");
            result.setCode (100072);
            result.setMsg ("询价单导入文件模板有误，请联系客服！");
            return result;
        }
        return result;
    }

    /**
     * 判断整行是否为空
     * @Author: liyang
     * @param row
     * @return
     */
    private  boolean isRowEmpty(Row row){
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK){
                return false;
            }
        }
        return true;
    }

    /**
     * @Description: 获取excel数据时对数据类型的判定及处理
     * @Author: chenyu.wang
     * @Params: [cell]
     * @Date: 2020.11.24 11:20
     */
    private String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        log.info("cellType========="+cell.getCellType());
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cellValue = cell.getStringCellValue().trim();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                //DecimalFormat df = new DecimalFormat("0");
                //cellValue = df.format(cell.getNumericCellValue());
                //log.info("num======================"+cell.getNumericCellValue());
                //cell.setCellType(CellType.STRING);
                log.info("------------------cellType"+cell.getCellType());
                cellValue = getRealStringValueOfDouble(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                cellValue = cell.getCellFormula();
                break;
            default:
                cellValue = "";
        }
        log.info("cellValue========="+cellValue);
        return cellValue;
    }

    private static String getRealStringValueOfDouble(Double d) {
        String doubleStr = d.toString();
        boolean b = doubleStr.contains("E");
        int indexOfPoint = doubleStr.indexOf('.');
        if (b) {
            int indexOfE = doubleStr.indexOf('E');
            BigInteger xs = new BigInteger(doubleStr.substring(indexOfPoint
                    + BigInteger.ONE.intValue(), indexOfE));
            int pow = Integer.valueOf(doubleStr.substring(indexOfE
                    + BigInteger.ONE.intValue()));
            int xsLen = xs.toByteArray().length;
            int scale = xsLen - pow > 0 ? xsLen - pow : 0;
            doubleStr = String.format("%." + scale + "f", d);
        } else {
            java.util.regex.Pattern p = Pattern.compile(".0$");
            java.util.regex.Matcher m = p.matcher(doubleStr);
            if (m.find()) {
                doubleStr = doubleStr.replace(".0", "");
            }
        }
        return doubleStr;
    }


    /**
     * 传入cell,获取cell值(String类型)
     * @param cell
     * @return
     */
//    public static String getCellValue(Cell cell) {
//        String cellValue = "";
//        // cell.getCellTypeEnum(),获取单元格类型,case不同类型进行不同处理
//        log.info("");
//        switch (cell.getCellTypeEnum()) {
//            case _NONE: // 未知类型，用于表示初始化前的状态或缺少具体类型。仅供内部使用。
//                break;
//            case NUMERIC: // 数字类型 小数,整数,日期
//                // 如果是数字类型的话,判断是不是日期类型
//                if (HSSFDateUtil.isCellDateFormatted(cell)) {
//                    // 获取日期类型的单元格的值
//                    Date d = cell.getDateCellValue();
//                    // 进行格式转换
//                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//                    cellValue = formatter.format(d);
//                } else {// 如果不是日期类型的单元格,那么将单元格格式设置成String,然后取值,这里可能会处问题,需要自己多尝试一下
//                    cell.setCellType(CellType.STRING);
//                    log.info("------------------cellType"+cell.getCellType());
//                    cellValue = cell.getStringCellValue();
//                }
//                break;
//            case STRING: // 字符串类型
//                cellValue = cell.getStringCellValue();
//                break;
//            case FORMULA: // 公式类型
//                cellValue = String.valueOf(cell.getNumericCellValue());
//                break;
//            case BLANK: // 空白的单元格
//                break;
//            case BOOLEAN: // 布尔类型
//                break;
//            case ERROR: // 错误类型
//                break;
//            default:
//                break;
//        }
//        return cellValue;
//    }

    /**
     * 同步固定申请平台砍价固定费率29.8（买家）
     * @return
     */
    @Override
    public List<ShopSysInvoiceDTO> getSynchronizationShopSysInvoiceBuy() {
        return baseMapper.getSynchronizationShopSysInvoiceBuy();
    }

    /**
     * 申请平台砍价
     * @param params
     * @param shopInfoDTO
     * @param userId
     * @param userName
     */
    @Transactional(rollbackFor=ServiceException.class)
    public void saveBatchPlatBargain(List<PlatBargainBO> params, ShopInfoDTO shopInfoDTO, Long userId, String userName){
        Long shopId = shopInfoDTO.getId();
        for(PlatBargainBO platBargainBO : params){

            if(platBargainBO.getPrice() == null || platBargainBO.getPrice().compareTo(BigDecimal.ZERO) <= 0){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainMapper.selectById(platBargainBO.getPurchaseCommodityBargainId());
            if(bargainDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            PurchaseInfoDTO purchaseInfoDTO = this.selectById(bargainDTO.getPurchaseId());
            if(purchaseInfoDTO == null){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            if(!purchaseInfoDTO.getShopId().equals(shopId)){
                throw new ServiceException(CodeEnum.FAIL_100057);
            }

            if(isFinishBargain(purchaseInfoDTO.getBargainStatus())){
                throw new ServiceException(CodeEnum.FAIL_100058);
            }

            if(isFinishBargain(bargainDTO.getBargainStatus())){
                throw new ServiceException(CodeEnum.FAIL_100058);
            }

            if(bargainDTO.getPlatBargainStatus() == 1 || bargainDTO.getPlatBargainStatus() == 2 || bargainDTO.getPlatBargainStatus() == 4){
                throw new ServiceException(CodeEnum.FAIL_100060);
            }

            //是否修改免费次数
            if(purchaseInfoDTO.getPurchaseFeeMoney().compareTo(BigDecimal.ZERO) > 0){
                if(purchaseInfoDTO.getPurchaseFeeMoneyStatus() != 2){
                    if(shopInfoDTO.getPurchaseFeeMoneyFreeTimes() > 0){
                        //修改报价服务费免费次数 及申请报价单砍价服务费
                        ShopInfoDTO newShopInfoDTO = new ShopInfoDTO();
                        int freeTimes = shopInfoDTO.getPurchaseFeeMoneyFreeTimes() - 1;
                        if(freeTimes < 0){
                            freeTimes = 0;
                        }
                        newShopInfoDTO.setPurchaseFeeMoneyFreeTimes(freeTimes);
                        Wrapper wrapper = new EntityWrapper();
                        wrapper.eq("id", shopId);
                        wrapper.eq("purchase_fee_money_free_times", shopInfoDTO.getPurchaseFeeMoneyFreeTimes());
                        boolean flag = shopInfoService.update(newShopInfoDTO, wrapper);
                        if(!flag){
                            throw new ServiceException(CodeEnum.FAIL_100070);
                        }
                        PurchaseInfoDTO newPurchaseInfoDTO = new PurchaseInfoDTO();
                        newPurchaseInfoDTO.setPurchaseFeeMoney(BigDecimal.ZERO);
                        newPurchaseInfoDTO.setPurchaseFeeMoneyStatus(2);
                        wrapper = new EntityWrapper();
//                        wrapper.eq("id", shopId);
                        wrapper.eq("id", purchaseInfoDTO.getId());
                        wrapper.eq("purchase_fee_money", purchaseInfoDTO.getPurchaseFeeMoney());
                        wrapper.eq("purchase_fee_money_status", purchaseInfoDTO.getPurchaseFeeMoneyStatus());
                        flag = this.update(newPurchaseInfoDTO, wrapper);
                        if(!flag){
                            throw new ServiceException(CodeEnum.FAIL_100070);
                        }

                        purchaseInfoDTO.setPurchaseFeeMoneyStatus(2);
                        purchaseInfoDTO.setPurchaseFeeMoney(BigDecimal.ZERO);
                    }
                }
            }


            PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
            newBargainDTO.setId(bargainDTO.getId());
            newBargainDTO.setUpdateUserName(userName);
            newBargainDTO.setUpdateUserId(userId);
            if(purchaseInfoDTO.getPurchaseFeeMoneyStatus() == 2){
                newBargainDTO.setPlatBargainStatus(2);
            } else {
                newBargainDTO.setPlatBargainStatus(1);
            }

            newBargainDTO.setPlatBargainPrice(platBargainBO.getPrice());
            newBargainDTO.setRevision(bargainDTO.getRevision());

            if(bargainDTO.getOneBargainPrice().compareTo(BigDecimal.ZERO) > 0){
                newBargainDTO.setWaitBargainPriceTimes(3);
            } else {
                newBargainDTO.setWaitBargainPriceTimes(2);
            }
            newBargainDTO.setPurchaseId(bargainDTO.getPurchaseId());

            updateBargainAndLogByRevision(newBargainDTO, shopId, 6, userId, userName, bargainDTO.getPrice(), platBargainBO.getPrice(), CodeEnum.FAIL_100054);

        }
    }


    private boolean isFinishBargain(int status){
        if(status == 1 || status== 2 || status == 3){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 报价事务
     * @param saveBO
     * @param shopInfoDTO
     * @param commodityDTO
     * @param commodityId
     * @param userId
     * @param userName
     */
    @Transactional(rollbackFor=ServiceException.class)
    public void saveBargain(PurchaseCommodityBargainSaveBO saveBO, ShopInfoDTO shopInfoDTO
            , PurchaseCommodityDTO commodityDTO, Long commodityId, Long userId, String userName){
        PurchaseCommodityBargainDTO bargainDTO = new PurchaseCommodityBargainDTO();
        bargainDTO.setPurchaseCommodityId(saveBO.getPurchaseCommodityId());
        bargainDTO.setShopId(shopInfoDTO.getId());
        bargainDTO = purchaseCommodityBargainMapper.selectOne(bargainDTO);
        if(bargainDTO == null){ //添加
            bargainDTO = new PurchaseCommodityBargainDTO();
            bargainDTO.setId(ymlConfig.getPkId());
            bargainDTO.setShopId(shopInfoDTO.getId());
            bargainDTO.setPurchaseId(commodityDTO.getPurchaseId());
            bargainDTO.setPurchaseCommodityId(saveBO.getPurchaseCommodityId());
            bargainDTO.setBargainStatus(0);
            bargainDTO.setCommodityName(commodityDTO.getCommodityName());
            bargainDTO.setBrandId(commodityDTO.getBrandId());
            bargainDTO.setCommodityId(commodityId);
            bargainDTO.setCommodityLogoUrl(commodityDTO.getCommodityLogoUrl());
            bargainDTO.setCommodityType(saveBO.getCommodityType());
            bargainDTO.setSpecificationModel(commodityDTO.getSpecificationModel());
            bargainDTO.setCreateUserName(userName);
            bargainDTO.setCreateUserId(userId);
            bargainDTO.setNum(commodityDTO.getNum());
            bargainDTO.setPrice(saveBO.getPrice());
            bargainDTO.setWarranty(saveBO.getWarranty());
            bargainDTO.setTotalPrice(saveBO.getPrice().multiply(BigDecimal.valueOf(commodityDTO.getNum())));
            bargainDTO.setSendName(saveBO.getSendName());
            bargainDTO.setSendMobile(saveBO.getSendMobile());
            bargainDTO.setSendAreaId(saveBO.getSendAreaId());
            bargainDTO.setSendAddress(saveBO.getSendAddress());
            bargainDTO.setSendDays(saveBO.getSendDays());
            bargainDTO.setFristScale(saveBO.getFristScale());
            bargainDTO.setFinalScale(saveBO.getFinalScale());
            bargainDTO.setStockDays(saveBO.getStockDays());
            bargainDTO.setOnePrice(saveBO.getPrice());
            bargainDTO.setBrandId(saveBO.getBrandId());//保存卖家报价时填写的品牌id
            bargainDTO.setSpecificationModel(saveBO.getSpecificationModel());//保存卖家报价时填写的规格型号
            bargainDTO.setPurchaseFeeMoney(commodityDTO.getPurchaseFeeMoney());
            bargainDTO.setPurchaseFeeMoneyScale(commodityDTO.getPurchaseFeeMoneyScale());
            bargainDTO.setPurchaseDividendScale(shopInfoDTO.getPurchaseDividendScale());

            if(commodityId == null){
                bargainDTO.setCommodityPublishType(1);
            } else {
                bargainDTO.setPurchaseDividendScale(getDividendScale(shopInfoDTO.getId(), commodityId));
            }

            Integer addFlag = purchaseCommodityBargainMapper.insert(bargainDTO);
            if(addFlag == null || addFlag != 1){
                throw new ServiceException(CodeEnum.FAIL_100054);
            }

            //添加日志
            insertCommodityBargainLog(bargainDTO.getPurchaseId(), bargainDTO.getId(), shopInfoDTO.getId(), 0, userId, userName, BigDecimal.ZERO, saveBO.getPrice(), CodeEnum.FAIL_100054);

        } else {
            //是否可以报价
            if(!(bargainDTO.getRefuseBargainStatus() == 0 && bargainDTO.getBargainStatus() == 0)){
                throw new ServiceException(CodeEnum.FAIL_100055);
            }
            if(bargainDTO.getPlatBargainStatus() == 1 || bargainDTO.getPlatBargainStatus() == 2){
                throw new ServiceException(CodeEnum.FAIL_100064);
            }

            BigDecimal oldPrice = bargainDTO.getPrice();
            PurchaseCommodityBargainDTO newBargainDTO = new PurchaseCommodityBargainDTO();
            newBargainDTO.setId(bargainDTO.getId());
            newBargainDTO.setCommodityId(commodityId);
            newBargainDTO.setCommodityLogoUrl(commodityDTO.getCommodityLogoUrl());
            if(commodityId == null){
                newBargainDTO.setCommodityPublishType(1);
                newBargainDTO.setPurchaseDividendScale(shopInfoDTO.getPurchaseDividendScale());
            } else {
                newBargainDTO.setCommodityPublishType(0);
                newBargainDTO.setPurchaseDividendScale(getDividendScale(shopInfoDTO.getId(), commodityId));
            }
            newBargainDTO.setBrandId(saveBO.getBrandId());
            newBargainDTO.setSpecificationModel(saveBO.getSpecificationModel());
            newBargainDTO.setCommodityType(saveBO.getCommodityType());
            newBargainDTO.setWarranty(saveBO.getWarranty());
            newBargainDTO.setUpdateUserName(userName);
            newBargainDTO.setUpdateUserId(userId);
            newBargainDTO.setNum(commodityDTO.getNum());
            newBargainDTO.setPrice(saveBO.getPrice());
            newBargainDTO.setTotalPrice(saveBO.getPrice().multiply(BigDecimal.valueOf(commodityDTO.getNum())));
            newBargainDTO.setSendName(saveBO.getSendName());
            newBargainDTO.setSendMobile(saveBO.getSendMobile());
            newBargainDTO.setSendAreaId(saveBO.getSendAreaId());
            newBargainDTO.setSendAddress(saveBO.getSendAddress());
            newBargainDTO.setSendDays(saveBO.getSendDays());
            newBargainDTO.setFristScale(saveBO.getFristScale());
            newBargainDTO.setFinalScale(saveBO.getFinalScale());
            newBargainDTO.setStockDays(saveBO.getStockDays());

            //修改报价或者第二次第三次报价
            int logType = 0;// 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价
            int times = 1;
            if(bargainDTO.getPlatBargainStatus() == 4){
                //第二次
                if(bargainDTO.getTwoPrice().compareTo(BigDecimal.ZERO) == 0){//第一次报价申请平台砍价 新增报价
                    logType = 2;
                    newBargainDTO.setTwoPrice(saveBO.getPrice());
                    times = 2;
                } else {
                    if(bargainDTO.getOneBargainPrice().compareTo(BigDecimal.ZERO) == 0){//第一次报价申请平台砍价 修改
                        logType = 2;
                        newBargainDTO.setTwoPrice(saveBO.getPrice());
                        times = 2;
                    } else {
                        logType = 4;
                        newBargainDTO.setThreePrice(saveBO.getPrice());
                        times = 3;
                    }
                }

                newBargainDTO.setPlatBargainStatus(5);//协调议价后报价
            } else {
                if(bargainDTO.getOneBargainPrice().compareTo(BigDecimal.ZERO) == 0){
                    newBargainDTO.setOnePrice(saveBO.getPrice());
                    times = 1;
                } else {
                    logType = 2;
                    newBargainDTO.setTwoPrice(saveBO.getPrice());
                    times = 2;
                }
            }
            newBargainDTO.setBargainPriceTimes(times);
            newBargainDTO.setRevision(bargainDTO.getRevision());
            newBargainDTO.setPurchaseId(bargainDTO.getPurchaseId());

            updateBargainAndLogByRevision(newBargainDTO, shopInfoDTO.getId(), logType, userId, userName, oldPrice, saveBO.getPrice(), CodeEnum.FAIL_100054);

        }
    }

    private BigDecimal getDividendScale(Long shopId, Long commodityId){
        ShopCategoryRelationDTO relationDTO = shopCategoryRelationService.getCategoryByShopIdAndCommodityId(shopId, commodityId);
        if(relationDTO == null){
            throw new ServiceException(CodeEnum.FAIL_100068);
        }
        return relationDTO.getDividendScale();
    }



    @Transactional(rollbackFor=ServiceException.class)
    public void updateBargainAndLogByRevision(PurchaseCommodityBargainDTO bargainDTO, Long shopId, Integer logType,
                                    Long userId, String userName, BigDecimal oldPrice, BigDecimal price,CodeEnum codeEnum){
        updateCommodityBargainDTO(bargainDTO, codeEnum);
        //添加日志 // 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价、9流标
        insertCommodityBargainLog(bargainDTO.getPurchaseId(), bargainDTO.getId(), shopId, logType, userId, userName, oldPrice, price, codeEnum);
    }

    private void updateCommodityBargainDTO(PurchaseCommodityBargainDTO bargainDTO, CodeEnum codeEnum){
        int revision = bargainDTO.getRevision();
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", bargainDTO.getId());
        wrapper.eq("revision", revision);
        bargainDTO.setRevision(revision + 1);

        Integer addFlag = purchaseCommodityBargainMapper.update(bargainDTO, wrapper);
        if(addFlag == null || addFlag != 1){
            throw new ServiceException(codeEnum);
        }
    }

    /**
     * 添加日志
     * @param bargainId
     * @param shopId
     * @param logType 0第一次报价、1第一次议价、2第二次报价、3第二次议价、4第三次报价、5拒绝议价、6申请平台议价、7取消报价、8完成报价、9流标,10平台砍价
     * @param userId
     * @param userName
     * @param oldPrice
     * @param price
     * @param codeEnum
     */
    private void insertCommodityBargainLog(Long purchaseId, Long bargainId, Long shopId, int logType, Long userId, String userName, BigDecimal oldPrice, BigDecimal price, CodeEnum codeEnum){
        PurchaseCommodityBargainLogDTO logDTO = new PurchaseCommodityBargainLogDTO();
        logDTO.setId(ymlConfig.getPkId());
        logDTO.setCommodityBargainId(bargainId);
        logDTO.setShopId(shopId);
        logDTO.setType(logType);
        logDTO.setCreateUserName(userName);
        logDTO.setCreateUserId(userId);
        logDTO.setMoney(oldPrice);
        logDTO.setMoneyBalance(price);
        logDTO.setPurchaseId(purchaseId);
        Integer addFlag = purchaseCommodityBargainLogMapper.insert(logDTO);

        if (addFlag == null || addFlag != 1) {
            throw new ServiceException(codeEnum);
        }
        if (logDTO.getType () != null){
            if(logDTO.getType () == 0 || logDTO.getType () == 2 || logDTO.getType () == 4){
                PurchaseInfoDTO purchaseInfoDTO = this.selectById (purchaseId);
                Long sellShopId = purchaseInfoDTO.getShopId ();
                asyncOrderService.sendPurchaseNotice (sellShopId,purchaseId);
            }
        }


    }

}
